Wiki Markup |
---|
When program execution enters a {{try}} block that has a {{finally}} block, the {{finally}} block always executes, regardless of whether the {{try}} block (or any associated {{catch}} blocks) execute to completion. Statements that cause the {{finally}} block to terminate abruptly also cause the {{try}} block to terminate abruptly, and consequently mask any exception thrown from the {{try}} or {{catch}} blocks \[[JLS 205, Section 14.20.2, Execution of try-catch-finally|http://java.sun.com/docs/books/jls/third_edition/html/statements.html#14.20.2]\]. |
Never use return
, break
, continue
or throw
statements within a finally
block.
...
Code Block | ||
---|---|---|
| ||
class TryFinally { private static boolean doLogic() { try { throw new IllegalStateException(); } finally { System.out.println("Caught Exception"); } // Any return statements must go here; applicable only when exception is thrown conditionally } public static void main(String[] args) { doLogic(); } } |
In If this example had a return
statement outside the finally
block, the compiler reports would report an error because the return
statement is would be unreachable due to the unconditional throwing of IllegalStateException
. If the exception were thrown conditionally, the return
statement could be used without compilation error.
...