Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / Java

Error Handling in Java

5.00/5 (10 votes)
29 Oct 2014CPOL4 min read 27.3K  
Get started with error and exception handling with Java programming

Errors can be divided into two categories:

  • Compile time errors
  • Run time errors

Compile Time Errors

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 be caught while writing code in the advanced editors or IDEs that are specially developed for writing Java code.

For example, let's take a simple example for declaring an integer variable.

Java
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 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 line#2 and fix the error.

Let's take another example from File handling.

Java
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 be able to compile the above code. Though there is no syntax error in the code, 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 Errors

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 run time when the application is actually executed by the 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 run time.

For example, let's take an example of a simple arithmetic operation.

Java
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 arithmetic exception at the line # where the integer type variable is divided by zero, i.e., int result = num1/num2;

Java
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 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 alternatives for the exception. If any exception occurs in the try block, then the control jumps to the catch block where you can output some custom message to the users or do some alternatives.

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.

Java
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 another Exception that 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.

Java
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.

Java
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.

Java
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. Hope this helps you in getting started with Exception handling in Java.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)