Java exception handling, aka. the try-catch-finally workflow

I was not completely sure about the order that try-catch-finally blocks are executed in (eg. if an exception occurs in a catch block, then is the immediatly following finally block executed next or the catch block that catches the exception?), so I made a small test case that demostrates workflow (order of execution) of the various blocks.

Here's the code:
public final class Test {
  public static void main(String[] args) {
    try {
      try {
        System.out.println("executing try block");
        throw new Exception("try block");
      } catch (Exception ex) {
        System.out.println("executing catch #1: caught exception from " + ex.getMessage());
        throw new Exception("catch #1");
      } finally {
        System.out.println("executing finally #1");
      }
    } catch (Exception ex) {
        System.out.println("executing catch #2: caught exception from " + ex.getMessage());
    } finally {
      System.out.println("executing finally #2");
    }
  }
}

And here's the output:
executing try block
executing catch #1: caught exception from try block
executing finally #1
executing catch #2: caught exception from catch #1
executing finally #2

The best way to know: try. Smile

P.S.: before you say I'm lame not to know the exact order Smile, try to search the answer on the net. I used the terms "java try catch finally" and also checked the official source (the Exception Handling chapter of the Java Language Specification), but it was still not trivial. To be honest, from the spec. I understood that in my example the second catch block (in the outer try-catch-finally construct) should be executed before the first finally block. Shock It's good that I've checked and now know it for sure.

P.S.2: I've tested this with both JDK 1.5 (Update 16) and JDK 1.6 (Update 10) and the results were the same (as I expected).

Comments

Comment viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.

Personal favorite

My personal favorite try-catch-finally blocks are those without the catch part: try-finally. When you don't care to handle the exception in a method - you do it elswhere - but want to do some finalization.