Java Exception Handling

Exceptions in Java are any abnormal, unexpected events or extraordinary conditions that may occur at runtime. They could be file not found exception, division by zero exception, unable to get database connection exception and so on. On such conditions Java throws an exception object. Java Exceptions are basically Java objects. It should be kept in mind that Java exceptions never occur at the compile time and they are nothing but the runtime errors.

Definition: – An exception is an unexpected event, which occurs during the execution of a program that interrupts the normal flow of the program’s instructions.  

When an exception occurs within a method, the method creates an object and hands it off to the runtime system. The object, called an exception object, contains information about the exceptional condition, including its type and the state of the program when it occurred. Creating an exception object and handing it to the runtime system is called throwing an exception.

After a method throws an exception, the runtime system attempts to find some mechanism to handle it. The set of possible “mechanisms” to handle the exception is the ordered list of methods that had been called to get to the method where the exception occurred. The list of methods is known as the call stack (see Figure 1 below).

Figure 1: The call stack of methods

The runtime system searches the call stack for a method that contains a block of code that can handle the exception. This block of code is called an exception handler. The search begins with the method in which the error occurred and proceeds through the call stack in the reverse order in which the methods were called. When an appropriate handler is found, the runtime system passes the exception to the handler. An exception handler is considered appropriate if the type of the exception object thrown matches the type that can be handled by the handler.

The exception handler chosen is said to catch the exception. If the runtime system exhaustively searches all the methods on the call stack without finding an appropriate exception handler, as shown in the Figure 2 below, the exception is caught by the default handler provided by the Java runtime system.

Figure 2: Searching the call stack for the exception handler

Any exception that is not caught by the program will ultimately be processed by the default handler. The default handler displays a string describing the exception, prints a stack trace from the point at which the exception occurred, and terminates the program.

Understanding the problem

To illustrate how an exception causes abnormal termination of execution of program, let us take a programming example. The following Java program (Except01.java) is syntactically correct and therefore there is no problem during compilation. But, while executing, it displays the following message (see the output below) and terminates without executing further statements.

public class Except01 {
    public static void main(String[] args) {
        int a = 10;
        int b = 0;
        int c = divide(a, b); //Division by zero
        System.out.println("c = " + c);
        int d = 100/10;
        System.out.println("d = " + d);
    }
static int divide(int a, int b) {
        return a/b;
    }
}

Output of the program is given below:

$ java Except01
Exception in thread "main" java.lang.ArithmeticException: / by zero
        at Except01.divide(Except01.java:11)
        at Except01.main(Except01.java:5)

The program works as follows:

When the Java runtime system detects the attempt to divide by zero (within divide() method), it constructs a new exception (i.e.  ArithmeticException) object and then throws this exception. This exception object passes onto its caller (the main() method). But, main() is not being able to handle this. Therefore, it causes the execution of Except01 to stop, because once an exception has been thrown, it must be caught by an exception handler and dealt with immediately. In this example, we haven’t supplied any exception handlers of our own, so the exception is caught by the default handler provided by the Java runtime system. The default handler displays a string describing the exception, prints a stack trace from the point at which the exception occurred, and terminates the program.

NOTE: The solution to the problem is given in the next section.