Java tutorials > Core Java Fundamentals > Exception Handling > How to handle multiple exceptions in one `catch`?
How to handle multiple exceptions in one `catch`?
catch blocks. Java 7 introduced a feature called 'multi-catch' which allows you to catch multiple exception types in a single catch block, simplifying exception handling and reducing code duplication. This tutorial explores the multi-catch feature and its advantages.
Basic Multi-Catch Syntax
catch block now handles both ArrayIndexOutOfBoundsException and NullPointerException. The exceptions are separated by the | (pipe) symbol. Inside the catch block, e is effectively final, meaning you cannot assign a new value to it. The type of e is the least specific type that's a supertype of all the exception types listed (in this case, something like RuntimeException or Exception, depending on the exceptions).
try {
// Code that might throw multiple types of exceptions
int[] numbers = {1, 2, 3};
int result = numbers[5]; // ArrayIndexOutOfBoundsException
String str = null;
str.length(); // NullPointerException
} catch (ArrayIndexOutOfBoundsException | NullPointerException e) {
System.err.println("An error occurred: " + e.getMessage());
}
Concepts Behind the Snippet
Throwable. Exception and Error are direct subclasses of Throwable. Multi-catch works with any combination of Exception subclasses.| symbol acts as a logical OR. If either ArrayIndexOutOfBoundsException or NullPointerException is thrown, the same catch block will execute.e is implicitly final. This means you cannot reassign it to a different exception instance or null.
Real-Life Use Case
IOException if the file is not found or cannot be read, and NumberFormatException if the file contains invalid data. A multi-catch block allows you to handle both scenarios in a single block.
try {
BufferedReader reader = new BufferedReader(new FileReader("data.txt"));
String line = reader.readLine();
int number = Integer.parseInt(line);
System.out.println("Number: " + number);
} catch (IOException | NumberFormatException e) {
System.err.println("Error processing file: " + e.getMessage());
}
When to Use Multi-Catch
catch blocks with nearly identical code, use a single multi-catch.
Best Practices
Exception or Throwable unless absolutely necessary. Catching specific exceptions allows you to handle errors more precisely.catch blocks.catch blocks to avoid unreachable code. This is not relevant for multi-catch, where the order doesn't matter.
Pros of Multi-Catch
Cons of Multi-Catch
Interview Tip
catch blocks. Understand when it's appropriate to use multi-catch and when it's better to use separate catch blocks. Mention that the exception variable within a multi-catch is implicitly final.
Alternatives
catch blocks for each exception type, often resulting in code duplication. Another approach was to catch a broader exception type (e.g., Exception) and then use instanceof checks to determine the specific exception type. However, this approach is generally less clean and maintainable than using multi-catch.
FAQ
-
Can I catch more than two exceptions in a single `catch` block?
Yes, you can catch any number of exceptions in a singlecatchblock by separating them with the|symbol. -
What happens if I try to assign a new value to the exception variable `e` inside the multi-catch block?
You will get a compile-time error because the exception variableeis implicitlyfinalwithin the multi-catch block. -
Is the order of exceptions in the `catch` clause important?
No, the order of exceptions in a multi-catch clause does not matter. Thecatchblock will execute if any of the specified exceptions are thrown. -
Can I use a multi-catch block to handle checked and unchecked exceptions together?
Yes, you can use a multi-catch block to handle any combination of checked and unchecked exceptions, as long as they are subclasses ofThrowable.