Clean • Professional
The Multi-Catch Block was introduced in Java 7 to allow developers to handle multiple exceptions in a single catch block, when those exceptions require the same handling logic.
Before Java 7, you had to write multiple catch blocks even if the code inside them was identical.
Before Java 7:
try {
// risky code
} catch (IOException e) {
handle();
} catch (SQLException e) {
handle();
}
After Java 7 (Multi-Catch Block):
try {
// risky code
} catch (IOException | SQLException e) {
handle();
}
A multi-catch block lets you catch multiple unrelated exceptions in a single catch block using the pipe ( | ) operator.
catch (IOException | SQLException e)
Use multi-catch when:
Syntax
try {
// risky code
} catch (ExceptionType1 | ExceptionType2 | ExceptionType3 e) {
// common handling code
}
import java.io.*;
import java.sql.*;
public class MultiCatchExample {
public static void main(String[] args) {
try {
int a = 10 / 0; // ArithmeticException
String s = null;
s.length(); // NullPointerException
} catch (ArithmeticException | NullPointerException e) {
System.out.println("Exception caught: " + e);
}
}
}
Exception caught: java.lang.ArithmeticException: / by zero
try {
readFile();
connectDatabase();
} catch (IOException | SQLException e) {
System.out.println("Operation failed: " + e.getMessage());
}
Not allowed:
catch (IOException | Exception e)
Exception is the parent of IOException.
finalNot allowed:
catch (IOException | SQLException e) {
e = new Exception(); // Error: e is final
}
Before Java 7:
catch (IOException e) { log(e); }
catch (SQLException e) { log(e); }
After Java 7:
catch (IOException | SQLException e) {
log(e);
}
Since exceptions are unrelated:
Both are valid:
catch (IOException | SQLException e)
catch (SQLException | IOException e)
| Feature | Multi-Catch Block | Multiple Catch Blocks |
|---|---|---|
| Code Duplication | None | Possible |
| Handling Logic | Same logic | Different logic |
| Readability | Clean & short | Longer |
| Introduced In | Java 7 | Java 1.0 |
| Good For | Same handling logic | Different logic per exception |
When each exception needs different handling:
catch (IOException e) {
handleFile();
}
catch (SQLException e) {
handleDatabase();
}
When exceptions have parent-child relationship.
Answer: To reduce repetitive code, improve readability, and simplify exception handling when multiple exceptions require the same handling logic.
Answer: No, Because Java cannot determine which type to assign to the exception variable due to parent-child hierarchy conflicts.