Nested Try-Catch in Java
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.
Java Program
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
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.
- 1The outer
tryblock wraps the whole sequence of risky operations. - 2Inside it, an inner
tryattemptsInteger.parseInt(input); its owncatch (NumberFormatException e)recovers by defaulting the value to0and printing a message, then execution continues normally. - 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. - 4That out-of-range access throws an
ArrayIndexOutOfBoundsException, which only the outercatch (ArrayIndexOutOfBoundsException e)can catch, since the inner try-catch has already finished running.
"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.