«Back to Home

Core Java

Topics

Multiple Catch In Java

Multiple catch blocks

If we want to do different tasks at the occurrence of the different exceptions, we need to use Java multi catch block.
 
A try block can have any number of catch blocks, i.e. written for catching the class Exception, which can catch all other exceptions.
 
Syntax

catch(Exception e){
//This catch block catches all the exceptions
}
  • When multiple catch blocks are present in a program, the catch block, shown above, should be placed at the last as per the exception handling.

  • When the try block is not throwing any exception, the catch block will be ignored, the program continues and if the try block throws an exception then, the appropriate catch block will catch it. All the statements in the catch block will be executed and then the program continues.
Let's see an example of multi-catch block.
 
Code
  1. package exceptionHandling;  
  2. public class MultipleCatchBlock {  
  3.     public static void main(String args[]) {  
  4.         try {  
  5.             int a[] = new int[10];  
  6.             a[15] = 100 / 0;  
  7.         } catch (ArithmeticException e) {  
  8.             System.out.println("ArithmeticException occurs");  
  9.         } catch (ArrayIndexOutOfBoundsException e) {  
  10.             System.out.println("ArrayIndexOutOfBoundsException occurs");  
  11.         } catch (Exception e) {  
  12.             System.out.println("Exception occurs");  
  13.         }  
  14.         System.out.println("Rest code...");  
  15.     }  
  16. }  
7

Output

8

Let’s see another example, given below.
 
Code
  1. package exceptionHandling;  
  2. public class MultipleCatchBlock {  
  3.     public static void main(String args[]) {  
  4.         try {  
  5.             int a[] = new int[8];  
  6.             a[10] = 50;  
  7.             System.out.println("Try block statement");  
  8.         } catch (ArithmeticException e) {  
  9.             System.out.println("ArithmeticException....");  
  10.         } catch (ArrayIndexOutOfBoundsException e) {  
  11.             System.out.println("ArrayIndexOutOfBoundsException.....");  
  12.         } catch (Exception e) {  
  13.             System.out.println("Some Other exception......");  
  14.         }  
  15.         System.out.println("Rest code...");  
  16.     }  
  17. }  
9

Output

10

In the example, mentioned above, there are multiple catch blocks in this program and these catch blocks executes in sequence, when an exception occurs in try block.
 
Summary
 
Thus, we learnt that if we have to do different tasks at the occurrence of different exceptions, we need to use Java multi catch block in Java and also learnt its rules.