tags:

views:

171

answers:

3

According to the Java Language Specification:

If there are any enclosing try statements whose try blocks contain the throw statement, then any finally clauses of those try statements are executed as control is transferred outward, until the thrown value is caught. Note that abrupt completion of a finally clause can disrupt the transfer of control initiated by a throw statement.

Other than returning inside a finally block, what other ways are there?

+6  A: 

Throwing an exception from a finally block will also clobber the original exception (if any).

EDIT: Found a reference explaining "abrupt completion".
From §14.1: Normal and Abrupt Completion of Statements:

An abrupt completion always has an associated reason, which is one of the following:

  • A break with no label
  • A break with a given label
  • A continue with no label
  • A continue with a given label
  • A return with no value
  • A return with a given value
  • A throw with a given value, including exceptions thrown by the Java virtual machine

The last three are the only ones possible in a finally clause, unless it is inside a loop.

Michael Myers
A: 

Sys.exit() or forcing an abort. GUI programs in particular are notorious for calling Sys.exit() on an exception, partly because of a bug that survived until JVM 1.5 --- an exception thrown from the GUI thread didn't make it over to the Main thread.

Update: especially to whomever downvoted this. Sorry, but Sys.exit() does exactly what is meant by abrupt termination including causing the stack not to be unwound; I'll be filing a bug against the documentation tomorrow. I can speak of this with some authority having been a Senior Java Architect at Sun for some years.

Charlie Martin
A: 

I guess it could also be a break statement inside a switch, if the finally block is part of a switch case. Also, if the finally block calls a method implemented in some other languages, it might do whatever the compiler of that language pleases.

Kim