Multi-catch

⭐ Interview Importance: MEDIUM
⏱️ Revision Time: 5 min

TL;DR

  • Introduced in Java 7, Multi-Catch allows you to catch multiple different exceptions in a single catch block.
  • It reduces code duplication when multiple exceptions require the exact same handling logic.
  • Syntax uses the pipe character | to separate exception types: catch (IOException | SQLException e).

Concept

Prior to Java 7, if your try block could throw an IOException and a SQLException, and you wanted to log an error and return for both, you had to write two identical catch blocks. Alternatively, you could catch a general Exception e, but that is bad practice as it might catch runtime bugs (like NullPointerException) that you didn’t intend to catch.

The Multi-Catch block solves this by letting you explicitly list the exceptions you want to handle together.

Examples

import java.io.IOException;
import java.sql.SQLException;

public class MultiCatchExample {
    
    // A dummy method that could throw two different checked exceptions
    public static void processData(int input) throws IOException, SQLException {
        if (input == 1) throw new IOException("File error");
        if (input == 2) throw new SQLException("DB error");
    }

    public static void main(String[] args) {
        
        // --- PRE-JAVA 7 WAY (Code Duplication) ---
        /*
        try {
            processData(1);
        } catch (IOException e) {
            System.err.println("Operation failed: " + e.getMessage());
        } catch (SQLException e) {
            System.err.println("Operation failed: " + e.getMessage());
        }
        */

        // --- JAVA 7 MULTI-CATCH WAY ---
        try {
            processData(1);
        } catch (IOException | SQLException e) {
            // Handles both elegantly
            System.err.println("Operation failed: " + e.getMessage());
            
            // Note: The variable 'e' is implicitly final. 
            // e = new IOException(); // This will not compile!
        }
    }
}

Interview Questions

Q: Can you catch an exception and its subclass in the same multi-catch block?
A: No. For example, catch (Exception | IOException e) will result in a compile-time error. Because IOException is a subclass of Exception, catching Exception already covers IOException. The compiler considers the second declaration redundant and invalid. You can only group exceptions that are disjoint (do not have a parent-child relationship).

Q: In a multi-catch block, is the exception variable mutable?
A: No. In a standard catch(IOException e) block, you could technically assign a new value to e (e.g., e = null). In a multi-catch block catch(IOException | SQLException e), the exception variable e is implicitly final. You cannot reassign it.