-3

The code snap is like below:

public static void main(String[] args) {
    System.out.println(echo("jjj"));
}

public static String echo(String str) {
    try {
        int a = 1/0;
    } catch (Exception e) {
        throw e;
    } finally {
        return str;
    }
}

Why can I get the output and no exception occurs?
And if I put the return clause out of finally, then exception occurs.
How could return(in finally) stop exception?

xuanzhui
  • 1,300
  • 4
  • 12
  • 30

1 Answers1

1

This behavior is specified pretty explicitly in the Java Language Specification section 14.20.2, which says:

A try statement with a finally block is executed by first executing the try block. Then there is a choice:

  • If execution of the try block completes normally, then the finally block is executed, and then there is a choice:

    • If the finally block completes normally, then the try statement completes normally.

    • If the finally block completes abruptly for reason S, then the try statement completes abruptly for reason S.

  • If execution of the try block completes abruptly because of a throw of a value V, then there is a choice:

    • If the run-time type of V is assignment compatible with a catchable exception class of any catch clause of the try statement, then the first (leftmost) such catch clause is selected. The value V is assigned to the parameter of the selected catch clause, and the Block of that catch clause is executed. Then there is a choice:

      • If the catch block completes normally, then the finally block is executed. Then there is a choice:

        • If the finally block completes normally, then the try statement completes normally.

        • If the finally block completes abruptly for any reason, then the try statement completes abruptly for the same reason.

      • If the catch block completes abruptly for reason R, then the finally block is executed. Then there is a choice:

        • If the finally block completes normally, then the try statement completes abruptly for reason R.

        • If the finally block completes abruptly for reason S, then the try statement completes abruptly for reason S (and reason R is discarded).

(Note that "throwing an exception" and "returning a value" count as "completing abruptly.")

Louis Wasserman
  • 191,574
  • 25
  • 345
  • 413