Java Catch Multiple Exceptions, Rethrow Exception With Examples

In Java 7, catch block has been improved to handle multiple exceptions in a single catch block. If you are catching multiple exceptions and they have similar code, then using this feature will reduce code duplication. Let’s understand java catch multiple exceptions feature with an example.

Java catch multiple exceptions

Before Java 7, we used to catch multiple exceptions one by one as shown below.

In Java 7, we can catch both these exceptions in a single catch block as:

If a catch block handles multiple exceptions, you can separate them using a pipe (|) and in this case, exception parameter (ex) is final, so you can’t change it. The byte code generated by this feature is smaller and reduce code redundancy.

Java rethrow exception

Another improvement is done in Compiler analysis of rethrown exceptions. Java rethrow exception allows you to specify more specific exception types in the throws clause of a method declaration.

Let’s see this with a small example:

As you can see that in rethrow method, catch block is catching Exception but it’s not part of throws clause. Java 7 compiler analyze the complete try block to check what types of exceptions are thrown and then rethrown from the catch block.

Note that this analysis is disabled if you change the catch block argument.

Further Reading: Exception Handling in Java.

By admin

Leave a Reply

%d bloggers like this: