πŸŽ‰ Special Offer !    Code: GET300OFF    Flat β‚Ή300 OFF on every Java Course
Grab Deal πŸš€

Multi-Catch Block in Java 7  


Introduction

  • Before Java 7, if a try block could throw multiple exceptions that needed similar handling, we had to write separate catch blocks (Multiple catch Blocks) for each exception.
  • This often resulted in duplicate code inside different catch blocks.
  • To reduce this redundancy, Java 7 introduced the Multi-Catch Block feature.
  • Definition:
    • A multi-catch block in Java is a feature (introduced in Java 7) that allows us to catch multiple exception types in a single catch block.
    • This is done using the pipe (|) operator between exception classes.
  • Syntax:
    • try
      {
          // risky code
      }
      catch (ExceptionClassType1 | ExceptionClassType2 ref_variable)
      {
          // handle both exceptions here
      }
  • Example:
    • import java.util.Scanner;
      import java.util.InputMismatchException;
      
      public class MainApp
      {
          public static void main(String[] args)
          {
              System.out.println("----- App Started -----");
      
              Scanner sc = new Scanner(System.in);
      
              try
              {
                  System.out.println("Enter no 1");
                  int no1 = sc.nextInt();
      
                  System.out.println("Enter no 2");
                  int no2 = sc.nextInt();
      
                  int res = no1 / no2;
                  System.out.println("Result : " + res);
              } 
              catch (InputMismatchException | ArithmeticException ex)
              {
                  System.out.println("Exception Occurred : " + ex);
              }
      
              System.out.println("----- App Finished Successfully -----");
          }
      }
      • Here we have used a single catch block to handle both InputMismatchException and ArithmeticException.

Points to remember for Multi-catch block:
  1. The exceptions listed in a multi-catch block must be unrelated (no parent-child relationship).
    • Example: IOException | SQLException βœ… allowed
    • Example: Exception | IOException ❌ not allowed (because IOException is a subclass of Exception).
  2. The exception variable (ex in the above example) is implicitly final, meaning you cannot reassign it inside the catch block.
    • catch (IOException | SQLException ex)
      {
          ex = new IOException(); // ❌ compile-time error
      }
  3. Multi-catch block helps in writing cleaner, shorter, and more maintainable code.