Java nested try block

As the name suggests, a try block within a try block is called nested try block in Java.

Why to use nested try block

This is needed when different blocks like outer and inner blocks may cause different errors. To handle them we need nested try blocks.

How exception handling works in nested try block

When nested try blocks are used, the inner try block is executed first. Any exception thrown in the inner try block is caught in the corresponding catch block. If a matching catch block is not found, then catch block of the outer try block are inspected. This process continues until all nested try statements are exhausted. If no matching catch block found, program terminates abnormally.

Syntax of nested try block

Example1 – nested try block

Output :

ArrayIndexOutOfBoundsException – Element at such index does not exists

Example2 – nested try block

Output :

ArrayIndexOutOfBoundsException – main try-block

Is the following nested try-catch block is an anti-pattern?

This is sometimes unavoidable, especially if your recovery code might throw an exception. Not pretty, but sometimes there are no alternatives.

Scroll to Top