Java ProgramsExceptionsNested Try-Catch

Nested Try-Catch in Java

intermediate·  Exceptions  ·  Error Handling

Problem

Nesting a try-catch inside another lets a narrow, specific failure recover locally without disturbing a broader operation around it, which still has its own fallback for anything else that goes wrong.

Parse one piece of input inside an inner try-catch, then use an array outside that inner block but still inside an outer try-catch guarding a separate operation.

Input
input="abc", arr={1, 2, 3}, index=5
Output
Inner catch: 'abc' is not a valid number, defaulting to 0 Outer catch: Index 5 is out of bounds

Java Program

Java
public class NestedTryCatch { public static void main(String[] args) { String input = "abc"; int[] arr = {1, 2, 3}; int index = 5; try { int number; try { number = Integer.parseInt(input); } catch (NumberFormatException e) { // Recovers locally — execution continues with a default value number = 0; System.out.println("Inner catch: '" + input + "' is not a valid number, defaulting to " + number); } int value = arr[index]; // not protected by the inner catch — a separate risky operation System.out.println("Value: " + value); } catch (ArrayIndexOutOfBoundsException e) { System.out.println("Outer catch: Index " + index + " is out of bounds"); } } }

Output

Inner catch: 'abc' is not a valid number, defaulting to 0 Outer catch: Index 5 is out of bounds

Core Logic

An inner try-catch recovers from one specific, expected failure and lets execution continue, while the surrounding outer try-catch still guards against anything else going wrong further down.

How It Works
  1. 1The outer try block wraps the whole sequence of risky operations.
  2. 2Inside it, an inner try attempts Integer.parseInt(input); its own catch (NumberFormatException e) recovers by defaulting the value to 0 and printing a message, then execution continues normally.
  3. 3After the inner try-catch finishes, the outer block goes on to access arr[index], a separate risky operation not protected by the inner catch.
  4. 4That out-of-range access throws an ArrayIndexOutOfBoundsException, which only the outer catch (ArrayIndexOutOfBoundsException e) can catch, since the inner try-catch has already finished running.
Parsing "abc" fails and is handled locally by the inner catch, printing its own message and defaulting to 0; then accessing arr[5] on a 3-element array fails too, this time caught by the outer catch.
💡

Key Point: The inner catch only ever sees exceptions thrown inside the inner try block — the array access happens after the inner try-catch has already completed, so only the outer catch is in scope to handle it.

Key Concepts

nested try / catchlocal recoveryfallback handling

Related Programs