Error Handling in Java

Errors can be divided into two categories.
  • Compile time error
  • Run time error

Compile time error 

Compile time errors are also known as design time errors. This can be a syntax error or can be an error in the code design. These kind of errors can easily caught while writing codes in the advanced editors or IDEs that are specially developed for writing Java codes.
For example let's take a simple example for declaring a integer variable.
public static void main(String[] args) {

    int num1 = 50

    System.out.println("The number is " + num1);

}
Now if I type this code in my IDE or if I compile the above java code file then it will immediately show me an error indicator on the line #2 i.e int num1 = 50
Because there is a wrong syntax in that line. I have not ended the statement with a semi colon ";". So I will get a compilation error when I try to compile the above code. And the developer can easily go to the line#2 and fix the error.
Let's take another example from File handling.
public static void main(String[] args) {

    // The program assumes the file path as a parameter or argument.
    // Get the file path into the variable
    String fileName=null;

    if(args!=null && args.length>0){
        fileName=args[0];

    }

    // Read the file and write some text into the file.
    File file = new File (fileName);
    OutputStreamWriter writer = new OutputStreamWriter( new FileOutputStream(file) );
    writer.write( "Hello World" );
    writer.close();
}
Now the above code looks good without any syntax error. But again java will not able to compile the above code. Though there is no syntax error in the code but there are some exceptions in the code structure. Just think if the File you are looking for in the program, doesn't exist in the given location. 
If you try to compile this code, it will give you few Exceptions saying that FileNotFoundException and IOException should be caught or handled.

Run time error

Runtime errors are known as logical errors which cannot be caught in the editors or while compiling the source code. Java will able to compile the source code successfully and generate the binary .class files, because everything looks good to the compiler both syntactically and structurally.
These errors occurred in the run time when the application is actually executed by end user.
The runtime errors normally occurred due to some fault in your code logic or due to invalid inputs provided to the application, which the application is not expected or designed to receive. These errors can break or crash your application logic in the run time.
For example let's take an example of a simple arithmetic operation.
public static void main(String[] args) {
    if(args!=null && args.length>1){
        int num1 = Integer.parseInt(args[0]);
        int num2 = Integer.parseInt(args[1]);
        
        int result = num1/num2;
        
        System.out.println(num1 + "/" + num2 + " = " + result);
    }
}
The above program accepts two numbers as arguments and divides the 1st number by the 2nd number.
Java will compile the above source code without any compilation error and generate the .class file.
Let's consider a case when the user runs the application with passing 0 as the 2nd argument.
Then it will give the user a Run time error on "divide by zero", as anything divide by zero is undefined. It will return the following arithmatic exception at the line # where the integer type variable is divided by zero i.e int result = num1/num2;
Exception in thread "main" java.lang.ArithmeticException:

So the developers should always take precautions in their code by handling the Exceptions that may occur during the run time. This will prevent their program from crashing and the application will run flawless even if some part of the application program fails to execute.

Handling Exceptions

Exceptions can be handled by using 'try-catch' block. Try block contains the code where you suspect that there might be exceptions. The catch block contains the alternates for the exception. If any exception occurs in the try block then the control jumps to catch block where you can output some custom message to the users or do some alternates.
Let's see how we can handle the run time exception in the first example i.e "divide by zero" by using try-catch block.
public static void main(String[] args) {

    if(args!=null && args.length>1){

        try {
            int num1 = Integer.parseInt(args[0]);
            int num2 = Integer.parseInt(args[1]);
    
            int result = num1/num2;
    
            System.out.println("The result is " + result);
        } catch (Exception e) {
            System.out.println(e.getMessage());
    
        }
    }

}
Again there can be other Exception occurred in the above code. Such as if the user passes two strings instead of two numbers.
So it is better if you can be specific on your Exceptions.
public static void main(String[] args) {

    if(args!=null && args.length>1){
        try {
            int num1 = Integer.parseInt(args[0]);
            int num2 = Integer.parseInt(args[1]);

            int result = num1/num2;
            System.out.println(num1 + "/" + num2 + " = " + result);
        }
        catch (NumberFormatException e) {
            // If the arguments cannot not parsed as integers.
            System.out.println("Enter numeric values only.");
        }
        catch (ArithmeticException e) {
            // If the arithmetic operation (divide by) is failed.
            System.out.println("Undefined result.");
        }
        catch (Exception e) {
            // If any other exception occurred.
            System.out.println(e.getMessage());
        }
    }

}
Let's see how we can handle the compile time exception in the second example i.e "File handling example" by using try-catch block.
public static void main(String[] args) {

    File file = new File ("MyTextFile.txt");
    try {
        OutputStreamWriter writer = new OutputStreamWriter( new FileOutputStream(file) );
        // Do your stuffs here...
        // I will just write steps to write some text into the file.
        writer.write( "Hello World" );
        writer.close();
    } catch (FileNotFoundException e) {
        // If file not found then control goes here
        System.out.println("File not found");
    } catch (IOException e) {
        // Catch block for other IO Exceptions;
    }

}
Java 7 has made it much easier with writing less code.
This will automatically close the stream at the end of the try block, you don't have to write a step to close the file.
try ( OutputStreamWriter writer = new OutputStreamWriter(new FileOutputStream(file)) ) {
    writer.write( "Hello World" );
} catch (FileNotFoundException e) {
    // If file not found then control goes here
    System.out.println("File not found");
} catch (IOException e) {
    // Catch block for other IO Exceptions;
}
These are some code examples on handling compilation and run time errors in Java programming.

No comments:

Post a Comment

Genuine websites to earn money.

If you are interested in PTC sites then this article is for you. I have personally tried many of the sites and found that the best thing ...