Example Illustrating Exception – try with multiple catch, nested try and finally block

1.3K views 5 minutes read
A+A-
Reset

Example Illustrating Exception case 3 try with multiple catch:

In last topic we have discussed two example programs illustrating exception handling.

In this case I wanna present a program with multiple catch blocks with a single try block.

package packOne;

public class MainWala {

	public static void main(String[] args) {
		
		try{  
		   
		    System.out.println("going to divide");  
		    int a[]=new int[5];  
		    a[5]=4;  
		    
		  }catch(ArrayIndexOutOfBoundsException e){
                    System.out.println(e);  
		     
		    System.out.println("other statement");  
		
	     }
		  catch(Exception e){
			  System.out.println("handeled");
		  } 
		  System.out.println("normal flow..");  		
	}  

}

Observe Output :

Then we will discuss about conclusions from this examples.

going to divide
java.lang.ArrayIndexOutOfBoundsException: 5
other statement
normal flow..

There are two catch blocks associated with single try block. When exception occurs jvm will look for a catch block sequentially in program. When it find a catch block, it checks whether that catch block can handle the exception or not. For example if NullPointerException occur inside try block and there is catch block with ArithmeticException, then that catch block can not handle exception. In such case jvm will look for another catch and so on.

Conclusions:

  1. There can be multiple catch block following a single try block.
  2. If catch block can accept the object of exception occurred, then only exception is handled.
  3. We must care about order of catch blocks.
  4. Catch block with specific exception should be placed first.
  5. Catch blocks with more specific exception should be placed later. Ex. Catch with ArithmeticException must be placed before the catch with Exception.
  6. Otherwise compile will show error since later catch block will become unreachable.(Look example below)

Here is code related to conclusion no 6. This code will produce compile time error.

package packOne;

public class MainWala {

	public static void main(String[] args) {
		
		try{  
		   
		    System.out.println("going to divide");  
		    int a[]=new int[5];  
		    a[5]=4;  
		    
		  }catch(Exception e){
			  System.out.println("handeled");
		  } 
		catch(ArrayIndexOutOfBoundsException e){System.out.println(e);  
		     
		    System.out.println("other statement");  
		
	     }
		  
		    System.out.println("normal flow..");  		
	}  

}

This will show compile time error saying “Unreachable catch block for ArrayIndexOutOfBoundException, It is already handled by catch block for Exception.”

Example Illustrating Exception case 4 Nested try:

Here is example for nested try block. Nested try means try block inside another try block. let’s have a look inside this example.

package packOne;

public class MainWala {

	public static void main(String[] args) {
		
		try{  
		   
		    System.out.println("first statement");  
		    int array[]=new int[5];  
		    
		    try{
		    	System.out.println("Division result "+23/0);
		        }catch(Exception e){
				  System.out.println("Inner try block handled "+e.getMessage());
			}
		    
		        array[5]=67;

		}catch(ArrayIndexOutOfBoundsException e){
		
		        System.out.println("outer try block handled "+e.getMessage());  
		
	     }
		
		  System.out.println("normal flow..");  		
	}  

}

In this case there are two try blocks. One inside another.

Observe Output:

first statement
Inner try block handled / by zero
outer try block handled 5
normal flow..

Conclusions from this examples:

  1. Nested try is allowed.
  2. There may be more than one try-catch blocks inside a try block.
  3. If exception occurred in any inner try block and catch clause cannot handle the exception then program will terminated.

Example Illustrating Exception case 5 finally bock:

In this case I’ll show a code showing finally block. For each try there may be at most one finally block. Lets have a look at following code.

package packOne;

public class MainWala {

	public static void main(String []args){
		
		System.out.println("starting codes ");
		try{
			
			System.out.println("risky code "+23/0);
			
		}catch(NullPointerException e){
			
			System.out.println(e.getMessage());
			
		}catch(Exception e){
			
			System.out.println(e.getMessage());
			
		}finally{
			System.out.println("Finally i'm important");
		}
		
		System.out.println("Other code");
	}
  

}

Observe the output:

starting codes 
/ by zero
Finally i'm important
Other code

From above example we can conclude that:

  1. For each try block there is only finally block.
  2. Finally block will be executed in any case, Whether exception occur or not.
  3. Generally finally block used to keep cleanup code like closing connections and resources.
  4. More than one finally in not allowed for a try block.
  5. try with finally block is also allowed without catch. See example below.
package packOne;

public class MainWala {

	public static void main(String []args){
		
		System.out.println("starting codes ");
		try{
			
			System.out.println("risky code "+23/0);
			
		}finally{
			System.out.println("Finally i'm important");
		}
		
		System.out.println("Other code");
	}
  

}

 

Output will be like this:

starting codes 
Exception in thread "main" Finally i'm important
java.lang.ArithmeticException: / by zero
	at packOne.MainWala.main(MainWala.java:10)

This example illustrates finally with try and without catch is allowed.

 

Lets take care of conclusion again. try must be paired with either catch or finally block or both. Multiple catch block are allowed with single try But keep mind of order. Multiple finally block is not allowed. And at last Finally before catch is not allowed.

Hope Example Illustrating Exception article help you to make clear idea about exception handling. Do comment in case of any confusion.

Leave a Reply

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More

Index

Adblock Detected

Please support us by disabling your AdBlocker extension from your browsers for our website.