Java allows multiple exceptions to be handled within a single catch block using the multi-catch feature introduced in Java 7. This is useful when different exception types require the same handling logic, reducing code duplication and improving readability.
Key Points: • Multiple exception types can be handled in one catch block using the pipe (|) operator. • The same error-handling code is executed regardless of which exception is thrown. • Multi-catch reduces duplicate code and improves maintainability. • Exceptions listed in a multi-catch block must not have a parent-child relationship. • The exception variable in a multi-catch block is implicitly final and cannot be reassigned.
Example: If both file operations and database operations require the same logging and cleanup process, they can be handled using a single catch block.
Code Example:
import java.io.IOException;
import java.sql.SQLException;
public class Demo {
public static void main(String[] args) {
try {
// Code that may throw IOException or SQLException
} catch (IOException | SQLException e) {
System.out.println("Exception handled: " + e.getMessage());
}
}
}Benefits of Multi-Catch: • Less code duplication • Improved readability • Easier maintenance • Consistent exception handling
Interview Tip: A concise interview answer is:
"Multiple exceptions can be handled in a single catch block using the pipe (|) operator. This feature, known as multi-catch, is useful when different exceptions require the same handling logic, helping reduce duplicate code and improve maintainability."