Handling multiple exceptions with multi-catch

In Java, we can handle multiple exceptions using a multi-catch block, which was introduced in Java 7. This feature allows us to catch multiple exceptions in a single catch block, reducing redundancy and making the code cleaner.

Syntax

Here, ExceptionType1, ExceptionType2, and ExceptionType3 are different types of exceptions we want to catch. The pipe (|) symbol separates the exception types. The variable e can then be used to handle the exceptions inside the catch block, and it will be of a common superclass type (e.g., Exception).

Example

  • Multiple exceptions: The exceptions in the multi-catch block must be unrelated, meaning they should not have a parent-child relationship. For example, IOException | SQLException is valid, but IOException | FileNotFoundException is not allowed because FileNotFoundException is a subclass of IOException.
  • Final variable: The exception variable in the multi-catch block is implicitly final, meaning we cannot reassign it after it’s caught.