Handling Multiple Exceptions with Multiple Catch Blocks in Java: A Comprehensive Guide

Rumman Ansari   Software Engineer   2024-07-04 04:48:35   7306  Share
Subject Syllabus DetailsSubject Details
☰ TContent
☰Fullscreen

Table of Content:

Multiple catch block

In some cases, more than one exception could be raised by a single piece of code. To handle this type of situation, you can specify two or more catch clauses, each catching a different type of exception. When an exception is thrown, each catch statement is inspected in order, and the first one whose type matches that of the exception is executed. After one catch statement executes, the others are bypassed, and execution continues after the try/catch block.

class Excptn
{
 public static void main(String[] args)
 {
  try
  {
   int arr[]={1,2};
   arr[2]=3/0;
  }
  catch(ArithmeticException ae)
  {
   System.out.println("divide by zero");
  }
  catch(ArrayIndexOutOfBoundsException e)
  {
   System.out.println("array index out of bound exception");
  }
 }
}
divide by zero
Press any key to continue . . .

Although both ArrayIndexOutOfBoundsException and ArithmeticException occured, but since first catch is of Arithmetic Exception, It will be caught there and program control will be continued after the catch block.

Note: At a time, only one exception is processed and only one respective catch block is executed.

public class MultipleCatchBlock{
  public static void main(String args[]){
   try{
    int a[]=new int[7];
    a[7]=60/0;
   }
   catch(ArithmeticException e){
	   System.out.println("task1 is completed");
	   }
   catch(ArrayIndexOutOfBoundsException e){
	   System.out.println("task 2 completed");
	   }
   catch(Exception e){
	   System.out.println("common task completed");
	   }

   System.out.println("rest of the code...");
 }
}
task1 is completed
rest of the code...
Press any key to continue . . .

All catch blocks must be ordered from most specific to most general i.e. catch for ArithmeticException must come before catch for Exception .

Example for Unreachable Catch block

While using multiple catch statements, it is important to remember that sub classes of class Exception inside catch must come before any of their super classes otherwise it will lead to compile time error. This is because in Java, if any code is unreachable, then it gives compile time error.

class Excptn
{
 public static void main(String[] args)
 {
  try
  {
   int arr[]={1,2};
   arr[2]=7/0;
  }
  catch(Exception e)    //This block handles all Exception
  {
   System.out.println("Generic exception");
  }
  catch(ArrayIndexOutOfBoundsException e)    //This block is unreachable
  {
   System.out.println("array index out of bound exception");
  }
 }
}

Compile time error

C:\Users\Hello World\Documents\Excptn.java:14: error: exception ArrayIndexOutOfBoundsException has already been caught
  catch(ArrayIndexOutOfBoundsException e)    //This block is unreachable
  ^
1 error

Tool completed with exit code 1

If you try to compile this program, you will receive an error message stating that the second catch statement is unreachable because the exception has already been caught. Since ArithmeticException is a subclass of Exception, the first catch statement will handle all Exception-based errors, including ArithmeticException. This means that the second catch statement will never execute. To fix the problem, reverse the order of the catch statements.

class MultipleCatchBlock{
  public static void main(String args[]){
   try{
    int a[]=new int[5];
    a[5]=30/0;
   }
   catch(Exception e){
	   System.out.println("common task completed");
	   }
   catch(ArithmeticException e){
	   System.out.println("task1 is completed");
	   }
   catch(ArrayIndexOutOfBoundsException e){
	   System.out.println("task 2 completed");
	   }
   System.out.println("rest of the code...");
 }
}

Compile time error

C:\Users\Hello World\Documents\MultipleCatchBlock.java:8: error: exception ArithmeticException has already been caught
   catch(ArithmeticException e){System.out.println("task1 is completed");}
   ^
C:\Users\Hello World\Documents\MultipleCatchBlock.java:9: error: exception ArrayIndexOutOfBoundsException has already been caught
   catch(ArrayIndexOutOfBoundsException e){System.out.println("task 2 completed");}
   ^
2 errors

Tool completed with exit code 1