Nested Try Block in Java

Naveen AnamaneniUpdated · 4 min read
easyJava 25javaexceptions

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

Marks.java▶ Try it
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);
    }
}
Output
Entries: 3
  skipping bad entry: 9O
Total: 155
No marks were given at all

How it works

  1. The inner try wraps one entry. "9O" (a letter O, not a zero) fails, the inner catch skips it, and the loop moves on.
  2. The outer try wraps the whole job. When marks is null, marks.length throws NullPointerException at the very start.
  3. 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 thrownInner catch matches?What happens
Inside the inner tryYesInner catch runs; the outer code continues
Inside the inner tryNoThe outer catch is checked next
Inside the outer try, outside the inner one(not involved)The outer catch is checked
Anywhere, no catch matchesNoThe 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.

Flatter.java▶ Try it
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);
    }
}
Output
  skipping bad entry: 9O
Total: 155

Common 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

  1. Easy: Change process so the inner catch also counts how many entries were skipped, and prints the count at the end.
  2. 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.

Quick check: Nested try

4 questions
1Which catch handles an exception thrown inside the inner try?
2If the inner catch doesn't match, what happens?
3When is nesting most useful?
4How can deep nesting be avoided?

Key Takeaways

Was this tutorial helpful?

Lesson 221 of 482