Multiple catch block in java

In the previous post, we have seen Nested try blocks. In this post, we will see if it is possible to have multiple catch block or not.

Can we have multiple catch block associated with one try block?

Answer is yes. We can have multiple catch block with a try block.

What is the purpose of having multiple catch block?

If a program can throw multiple exceptions, then it can be handled by using multiple catch blocks. Each catch block will hold a specific type of exceptions which may occur in the program.

Let’s understand this with an example.

Output: Null pointer exception

Explanation of the example:

In the above example, we have multiple catch blocks i.e to be precise 3 blocks. Which are handling Arithmetic exception, NullointerException and in third block we have taken parent class of all exceptions i.e. Exception class.

When program executes the below line, a nullpointerException occurs. Because we are trying to get the length of the variable whose value is actually null.

In this case, the controls goes to catch block which is handling NullPointerException. In the program, for the next line we are supposed to get Arithmetic exception but that line never executed because it can executes only one catch block at a time. So, remaining catch blocks did not get executed.

Note: At a time only one exception can occur, so only one catch block is executed.

Important point to note:

The order of catch blocks must be arranged from most specific to most general i.e. catch block for ArithmeticException must come before catch for Exception . Let’s understand with the example.

Compile Time error: Unreachable catch block for NullPointerException. It is already handled by the catch block for Exception
Unreachable catch block for ArithmeticException. It is already handled by the catch block for Exception
Ask Question
If you have any question, you can go to menu ‘Features -> Q&A forum-> Ask Question’.Select the desired category and post your question.
Print Friendly, PDF & Email
Nested try block in java
Throw and Throws keywords in java
Shekhar Sharma

Shekhar Sharma

Shekhar Sharma is founder of testingpool.com. He is an automation engineer having more than 8 years of experience who loves troubleshooting in automation and finding innovative ways to solve the problems. His other leisurely activities includes playing harmonica, paintings, sketching portrait, watching movies and travelling etc.

You may also like...