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
1 2 3 4 5 |
try { // code that might throw exceptions } catch (ExceptionType1 | ExceptionType2 | ExceptionType3 e) { // Handle multiple exceptions } |
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
1 2 3 4 5 6 7 8 9 10 11 12 |
public class MultiCatchExample { public static void main(String[] args) { try { int[] arr = new int[5]; arr[10] = 10; // This will throw ArrayIndexOutOfBoundsException String str = null; System.out.println(str.length()); // This will throw NullPointerException } catch (ArrayIndexOutOfBoundsException | NullPointerException e) { System.out.println("Exception caught: " + e); } } } |
- 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, butIOException | FileNotFoundException
is not allowed becauseFileNotFoundException
is a subclass ofIOException
. - Final variable: The exception variable in the multi-catch block is implicitly final, meaning we cannot reassign it after it’s caught.