0

I was studying for the OCA exam and I found a conflicting point while solving topics about Java exceptions. Here is the code causing my confusion:

public class StringOps {
    public static void main(String[] args) {
        System.out.print("a");
        try {
            System.out.print("b");
            throw new IllegalArgumentException();
        } catch (IllegalArgumentException e) {
            System.out.print("c");
            throw new RuntimeException("1");
        } catch (RuntimeException e) {
            System.out.print("d");
            throw new RuntimeException("2");
        } finally {
            System.out.print("e");
            throw new RuntimeException("3");
        }
    }
}

This code outputs: a-> b -> c -> e.

But I don't understand why? I thought it would output: a-> b -> c -> d -> e.

Any help would be greatly appreciated!

Nathan
  • 7,853
  • 4
  • 27
  • 50

1 Answers1

0

This happened because even though you threw a new RuntimeException, in your first catch block, this new RuntimeException is still subject to the finally clause from your first catch block.

If you wanted to hit multiple catches you would have to nest your try/catches. The control flow is always:

 try --> catch --> finally.

Hopefully that helps!

Nathan
  • 7,853
  • 4
  • 27
  • 50