Junior — Middle
Can you give an example where multiple different error types are caught in a single exception handling block?
sobes.tech AI
Answer from AI
Since Java 7, it is possible to catch multiple exceptions in a single catch block by listing them separated by the vertical bar |. This is convenient if the handling for different exceptions is the same.
Example:
try {
// code that may throw IOException or SQLException
} catch (IOException | SQLException e) {
System.out.println("An input/output or database error occurred: " + e.getMessage());
}
Here, one catch block handles two different types of exceptions at once.