Exception Handling how to

Java exception handling is used to handle exceptional conditions in a program systematically by taking the necessary actions. Therefore stated simply, the exception-handling capability of Java makes it possible for us to:

• Monitor for exceptional conditions within our program.

• Transfer control to special exception-handling code if an exceptional condition occurs.

This is accomplished using the keywords: try, catch, throw, throws, and finally.  The basic concept is as follows:

• We try to execute the statements contained within a block of code (exception thrower).

• We catch and process the exception object using code that we have designed (exception handler).

• If we want to create an exceptional condition explicitly within a block of code, we use the throw statement.

• The throws keyword is associated with a method signature to declare about exceptions that occur within a program.

• We optionally execute a block of code, designated by finally, which is executed to perform some type of cleanup operation.

A try and its catch statement form a unit. The scope of the catch clause is restricted to those statements specified by the immediately preceding try statement. A catch statement cannot catch an exception thrown by another try statement (except in the case of nested try statements). The statements that are protected by try must be surrounded by curly braces (that is, they must be within a block). We cannot use try on a single statement. The goal of most well-constructed catch clauses should be to resolve the exceptional condition and then continue on as if the error had never happened.

Remember that every try statement should be followed by at least one catch statement; otherwise compilation error will occur. Another important thing is that catch statement works like a method definition. The catch statement is passed a single parameter, which is reference to the exception object thrown (thrown by the try block). If the catch parameter matches with the type of exception object, then the exception is caught and the statements within the catch block will be executed. Otherwise, the exception is not caught and the default exception handler will cause the execution to terminate.

 

Finding the solution

After a method throws an exception, the runtime system attempts to find some mechanism to handle it. Java exception handling is used to handle exceptional conditions in a program systematically by taking the necessary actions. The purpose of exception handling mechanism is to provide a means to detect and report exceptional conditions so that appropriate actions can be taken. The exception handling mechanism basically consists of two segments, one to detect unexpected events and to throw exceptions and the other to catch exceptions and to take appropriate actions. This can be done in Java by using try-catch block.

 

Java “try-catch” block

Java uses the keyword “try” to preface a block of code that is likely to cause an abnormal condition and “throw” an exception. A “catch” block defined by the keyword catch “catches” the exception thrown by the try block and handles it appropriately. The catch block is added immediately after the try block. This is the general form of an exception-handling try-catch block:

try {
// block of code that generates an exception
}
catch (Exception-Type e) {
// block of code that handles the exception for Exception-Type
}
//Exception-Type is the type of exception that has occurred

The following code gives solution to the problem discussed in the previous section (Except02.java).

public class Except02 {
    public static void main(String[] args) {
        int a = 10;
        int b = 0;
        try { //exception thrower
          int c = divide(a, b);
          System.out.println("c = " + c);
        }
        catch(ArithmeticException e) { //exception handler
           System.out.println("Exception : "+e);
        }
        int d = 100/10;
        System.out.println("d = " + d);
    }
    static int divide(int a, int b) {
        return a / b;
    }
}

Output of the modified program:

$ java Except02
Exception : java.lang.ArithmeticException: / by zero
d = 10

The program works as follows:

Notice that the call to println( ) inside the try block is never executed. Once an exception is thrown, program control transfers out of the try block into the catch block. Put differently, catch is not “called,” so execution never “returns” to the try block from a catch. Thus, the line System.out.println(“The value of c = “+c) inside the try block is never displayed. Once the catch statement has executed, program control continues with the next line in the program following the entire try-catch mechanism. Here the call to println( ) inside the catch block displays the string representation of the ArithmeticException object e and the println( ) method call following the catch block shows the value of integer variable d as 10.