Nested Try Blocks In Java

Mouad Oumous
The Fresh Writes
Published in
6 min readFeb 14, 2023

In Java, a try statement can be inside the block of another try. It is called as nested try block. Each time a try statement is entered, the context of that exception is pushed on the stack.

Nested Try Blocks In Java

Why use nested try block

Sometimes a situation may arise where a part of a block may cause one error and the entire block itself may cause another error. In such cases, exception handlers have to be nested.

Syntax

try {
statement 1;
statement 2;
try {
statement 1;
statement 2;
}
catch(Exception e) {
// catch the corresponding exception
}
}
catch(Exception e) {
// catch the corresponding exception
}
.............

Example

// An example of nested try statements.
class NestTry {
public static void main(String args[]) {
try {
int a = args.length;
/* If no command-line args are present,
the following statement will generate
a divide-by-zero exception. */
int b = 42 / a;
System.out.println("a = " + a);
try { // nested try block
/* If one command-line arg is used,
then a divide-by-zero exception
will be generated by the following code. */
if(a==1) a = a/(a-a); // division by zero
/* If two command-line args are used,
then generate an out-of-bounds exception. */
if(a==2) {
int c[] = { 1 };
c[42] = 99; // generate an out-of-bounds exception
}
} catch(ArrayIndexOutOfBoundsException e) {
System.out.println("Array index out-of-bounds: " + e);
}
} catch(ArithmeticException e) {
System.out.println("Divide by 0: " + e);
}
}
}

As you can see, this program nests one try block within another. The program works as follows.

No command line : When you execute the program with no command-line arguments, a divide-by-zero exception is generated by the outer try block.

One command line argument : Execution of the program with one command-line argument generates a divide-by-zero exception from within the nested try block. Since the inner block does not catch this exception, it is passed on to the outer try block, where it is handled.

Two command-line arguments : If you execute the program with two command-line arguments, an array boundary exception is generated from within the inner try block. Here are sample runs that illustrate each case:

C:\>java NestTry
Divide by 0: java.lang.ArithmeticException: / by zero
C:\>java NestTry One
a = 1
Divide by 0: java.lang.ArithmeticException: / by zero
C:\>java NestTry One Two
a = 2
Array index out-of-bounds:
java.lang.ArrayIndexOutOfBoundsException:42

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

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

Side Notes

  • If an inner try statement does not have a matching catch statement for a particular exception, the control is transferred to the next try statement catch handlers that are expected for a matching catch statement.
  • This continues until one of the catch statements succeeds, or until all of the nested try statements are done.
  • If no one catch statements match, then the Java run-time system will handle the exception. Each time a try block does not have a catch handler for a particular exception, then the catch blocks of parent try block are inspected for that exception, if match is found that that catch block executes.If neither catch block nor parent catch block handles exception then the run-time system generated message would be shown for the exception, similar to what we see when we don’t handle exception.
  • 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 until all nested try statements are exhausted. If no matching blocks are found, the Java Runtime Environment handles the execution.

Program

// An example of nested try statements.
class NestTry {
public static void main(String args[]) {
try {
int a = args.length;
/* If no command-line args are present,
the following statement will generate
a divide-by-zero exception. */
int b = 42 / a;
System.out.println("a = " + a);
try { // nested try block
/* If one command-line arg is used,
then a divide-by-zero exception
will be generated by the following code. */
if(a==1) a = a/(a-a); // division by zero
/* If two command-line args are used,
then generate an out-of-bounds exception. */
if(a==2) {
int c[] = { 1 };
c[42] = 99; // generate an out-of-bounds exception
}
} catch(ArrayIndexOutOfBoundsException e) {
System.out.println("Array index out-of-bounds: " + e);
}
} catch(ArithmeticException e) {
System.out.println("Divide by 0: " + e);
}
}
}

As you can see, this program nests one try block within another. The program works as follows. When you execute the program with no command-line arguments, a divide-by-zero exception is generated by the outer try block. Execution of the program with one command-line argument generates a divide-by-zero exception from within the nested try block. Since the inner block does not catch this exception, it is passed on to the outer try block, where it is handled. If you execute the program with two command-line arguments, an array boundary exception is generated from within the inner try block. Here are sample runs that illustrate each case:

C:\>java NestTry
Divide by 0: java.lang.ArithmeticException: / by zero
C:\>java NestTry One
a = 1
Divide by 0: java.lang.ArithmeticException: / by zero
C:\>java NestTry One Two
a = 2
Array index out-of-bounds:
java.lang.ArrayIndexOutOfBoundsException:42

Nesting of try statements can occur in less obvious ways when method calls are involved. For example, you can enclose a call to a method within a try block. Inside that method is another try statement. In this case, the try within the method is still nested inside the outer try block, which calls the method. Here is the previous program recoded so that the nested try block is moved inside the method nesttry( ):

/* Try statements can be implicitly nested via
calls to methods. */
class MethNestTry {
static void nesttry(int a) {
try { // nested try block
/* If one command-line arg is used,
then a divide-by-zero exception
will be generated by the following code. */
if(a==1) a = a/(a-a); // division by zero
/* If two command-line args are used,
then generate an out-of-bounds exception. */
if(a==2) {
int c[] = { 1 };
c[42] = 99; // generate an out-of-bounds exception
}
} catch(ArrayIndexOutOfBoundsException e) {
System.out.println("Array index out-of-bounds: " + e);
}
}
public static void main(String args[]) {
try {
int a = args.length;
/* If no command-line args are present,
the following statement will generate
a divide-by-zero exception. */
int b = 42 / a;
System.out.println("a = " + a);
nesttry(a);
} catch(ArithmeticException e) {
System.out.println("Divide by 0: " + e);
}
}
}

The output of this program is identical to that of the preceding example.

Thanks for reading.Happy learning 😄

Join Mouad Oumous Java WhatsApp Group JOIN

Join Mouad Oumous Telegram Channel JOIN

Do support our publication by following it

--

--

Mouad Oumous
The Fresh Writes

I'm a blogger on medium, l'm a java and kotlin developer, also an Android Developer I mastered various topics such as Networking, UI , UX, Animation ...