Java Catch Multiple Exceptions

Java 7 introduced a new mechanism that makes it possible to catch multiple exceptions in the same catch block. This mechanism is commonly known as multi catch.

Before Java 7 introduced this new feature to catch multiple exception you would have to write something like this:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
private static void beforeJava7() {
    try {
        FileInputStream is = new FileInputStream(ResourceUtils.getFileFromResources("file.txt"));
    } catch(ResourceNotFoundException e) {
        e.printStackTrace();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

As you can see from the above code to catch multiple exceptions in Java we have to write individual catch blocks even though we handle the exceptions in the same way.

However from Java 7 we can catch multiple Java exceptions using the multi catch syntax.

1
2
3
4
5
6
7
8
9
private static void fromJava7() {
    try {
        FileInputStream is = new FileInputStream(ResourceUtils.getFileFromResources("file.txt"));
    } catch (IOException | ResourceNotFoundException e) {
        System.err.println("Error reading file");
    } catch (Exception e) {
        System.err.println("An unexpected error occurred");
    }
}

The multi catch construct allows you to catch multiple Java exceptions in the same catch block by separating them with the pipe character |.

Conclusion

In this short tutorial we saw how we can catch multiple exceptions in Java using the new multi catch construct introduced in Java 7.