Java-Catch Block Searching Algorithm

Catch Block Searching Algorithm

Consider a program in which the main( ) method calls the method One( ) and the method One( ) calls the method Two( ). Suppose that each one of these three methods contains a try block and the associated catch blocks. Suppose further that an error condition occurs during the execution of the code in the try block in the method Two( ). As we know, the JVM will now try to handle this error condition with the help of one of the catch blocks specified in the method Two( ). However, in some situations, it may so happen that none of the catch blocks in the method Two( ) is capable of handling the error condition that has occurred. In such situations, the JVM will not immediately invoke the default exception handling mechanism. Instead, it will continue the search for a suitable catch block by examining the catch blocks specified in the method One( ). If a matching catch block is not located in the method One( ) also, the search will continue in the method main( ). If a matching catch block is not found in the main( ) method also, the JVM will invoke the default exception handling mechanism.

It is to be noted here that the JVM tries its level best to handle an error condition with the help of an user-defined catch block. It invokes the default exception handling mechanism only as last resort.

Program

final

Program Source

class Javaapp {

    public static void main(String[] args) {
        
        try{
            System.out.println("Before Calling Method One");
            one();
            System.out.println("After Calling Method One");
            
        }catch(ArithmeticException ex){
            
            System.out.println("Exception : "+ex);  
        }
        System.out.println("Main Execution Complete");
    }
    
    static void one()
    {
        try{
            System.out.println("Before Calling Method Two");
            two();
            System.out.println("After Calling Method Two");
            
        }catch(ArrayIndexOutOfBoundsException ae){
           
            System.out.println(ae);  
        }
        System.out.println("Method One Execution Complete");        
    }
    
    static void two()
    {
        try{
            int dataArray[] = new int[5];
            dataArray[6] = 100;
            
        }catch(NullPointerException ne){
            
            System.out.println(ne);  
        }
        System.out.println("Method Two Execution Complete");        
    }    
}

Leave a Comment