Nested Try Block in Java
Sometimes one part of a task can fail without spoiling the whole task. When processing a list of marks, one bad entry shouldn't stop the others, but a missing list should stop everything. A nested try puts a try inside another try (or inside a catch), so small problems are handled close to where they happen and big problems are handled further out.
Inner and Outer Handlers
public class Marks {
static void process(String[] marks) {
try {
System.out.println("Entries: " + marks.length);
int total = 0;
for (String m : marks) {
try {
total += Integer.parseInt(m);
} catch (NumberFormatException e) {
System.out.println(" skipping bad entry: " + m);
}
}
System.out.println("Total: " + total);
} catch (NullPointerException e) {
System.out.println("No marks were given at all");
}
}
public static void main(String[] args) {
process(new String[] {"80", "9O", "75"});
process(null);
}
}Entries: 3
skipping bad entry: 9O
Total: 155
No marks were given at allHow it works
- The inner
trywraps one entry."9O"(a letter O, not a zero) fails, the inner catch skips it, and the loop moves on. - The outer
trywraps the whole job. Whenmarksisnull,marks.lengththrowsNullPointerExceptionat the very start. - The inner catch only handles
NumberFormatException, and it isn't even reached, so the exception goes to the outer catch.
How Java Searches for a Handler
| Where the exception is thrown | Inner catch matches? | What happens |
|---|---|---|
Inside the inner try | Yes | Inner catch runs; the outer code continues |
Inside the inner try | No | The outer catch is checked next |
Inside the outer try, outside the inner one | (not involved) | The outer catch is checked |
| Anywhere, no catch matches | No | The exception leaves the method (see "Exception Propagation in Java") |
When Nesting Helps, and When It Hurts
Nesting is useful when one item's failure shouldn't stop the batch, or when cleaning up after an error can itself fail (a try inside a catch or finally). Deep nesting, though, is hard to read. Two levels is usually the limit.
public class Flatter {
static int parseOrZero(String m) {
try {
return Integer.parseInt(m);
} catch (NumberFormatException e) {
System.out.println(" skipping bad entry: " + m);
return 0;
}
}
public static void main(String[] args) {
int total = 0;
for (String m : new String[] {"80", "9O", "75"}) {
total += parseOrZero(m);
}
System.out.println("Total: " + total);
}
} skipping bad entry: 9O
Total: 155Common Mistakes
Nesting three or four levels deep. Extract methods instead.
Catching the same exception at both levels without a reason. The inner one wins, and the outer one never sees it.
Using nested try to "retry" with copy-pasted code. A loop with a counter is clearer.
Practice
- Easy: Change
processso the inner catch also counts how many entries were skipped, and prints the count at the end. - Harder: Read a list of
"name:marks"strings. A bad marks value should skip one student; a missing colon should stop the whole report. Use nested try blocks, then refactor with a helper method.
Key Takeaways
Was this tutorial helpful?