Multiple catch block in java

we have seen how to use the catch block with try and some examples. Now we will see how we can use Multiple catch block in java but there are some rules to use multiple catches:
Rule 1: Compiler executes only one exception at a time all other blocks will be skipped automatically above shown in the above example.
Rule 2: When we use Multiple catch block in java, All catch blocks must be placed in the least generic to most generic ordered i.e. catch for ArithmeticException and NumberFormatException must come before catching for Exception. Because ArithmeticException and NumberFormatException are least generic than Exception. If we place the most generic catch block first, then the compiler gives an error in compilation.

Multiple catch block in java
public class UseOfTryAndMultipleCatchBlock
{  
  public static void main (String args[])
  {  
  	try
  	{   
		System.out.println("This code is inside in the try block");  
		int a = 2;
		int b = 0;
    	 	int c = a/b;  
		System.out.println("result of calculation = "+ c);  
  	}
	catch (Exception e)
  	{
       	e.printStackTrace();
		System.out.println("Exception are handled");  
  	}
   	catch (ArithmeticException e)
  	{
       	e.printStackTrace();
		System.out.println("ArithmeticException are handled");  
  	}
	catch (NumberFormatException e)
  	{
       	e.printStackTrace();
		System.out.println("NumberFormatException are handled");  
  	}
	   //rest code of the program   
  	 System.out.println("This code is outside from the try block");  
  }  
}  

Output: UseOfTryAndMultipleCatchBlock.java:18: error: exception ArithmeticException has already been caught catch (ArithmeticException e) UseOfTryAndMultipleCatchBlock.java:23: error: exception NumberFormatException has already been caught catch (NumberFormatException e)

Explanation of example: This is because we placed the generic exception catch block (Exception) in the first place which means all other catch blocks (ArithmeticException & NumberFormatException) placed after this block are unreachable. You should always place the most generic block at the end of all other specific exception catch blocks.

If you place a generic block at first, then the compiler will never able to reach any other block. Because generic catch block (Exception)can handle all the exceptions. Whether it is ArithmeticException or NumberFormatException or any other type of exception. An exception is super most class so it can handle all the subclass exceptions.

Leave a Comment