Can we define a try block with multiple catch blocks in Java?



Yes, we can define one try block with multiple catch blocks in Java.

  • Every try should and must be associated with at least one catch block.
  • Whenever an exception object is identified in a try block and if there are multiple catch blocks then the priority for the catch block would be given based on the order in which catch blocks are have been defined.
  • Highest priority would be always given to first catch block. If the first catch block cannot handle the identified exception object then it considers the immediate next catch block.

Example

class TryWithMultipleCatch {
   public static void main(String args[]) {
      try{
         int a[]=new int[5];
         a[3]=10/0;
         System.out.println("First print statement in try block");
      } catch(ArithmeticException e) {
         System.out.println("Warning: ArithmeticException");
      } catch(ArrayIndexOutOfBoundsException e) {
         System.out.println("Warning: ArrayIndexOutOfBoundsException");
      } catch(Exception e) {
         System.out.println("Warning: Some Other exception");
      }
      System.out.println("Out of try-catch block");
   }
}

Output

Warning: ArithmeticException
Out of try-catch block

Advertisements