Multiple Catch Blocks in Java

In this tutorial, we will learn about Multiple Catch Blocks in Java.

In Java, we handle the Exceptions using try-catch block. A method might throw multiple exceptions depending on the code in it. To handle this situation, we need to specify more than 1 catch block where each catch block is handling different type of exception.

When an exception is thrown, each catch statement is inspected in order, and the first one whose type matches that of the exception is executed. After one catch statement executes, the others are bypassed, and execution continues after the try/catch block.

Let’s see this with an example.

Example of Multiple Catch Blocks in Java:

Output:

Here in this program, the statement

throws Null pointer exception.

The above statement can cause Arithmetic exception.
To Handle these two different types of exception, we have included below two catch blocks after try block.

In the above program, when the exception occurs each catch statement is checked and the matching catch block will get executed.

Please note that at a time only 1 catch block will get executed and at a time only 1 exception can be handled.

Related posts

Leave a Comment