Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

Never use return, break, continue, or throw statements within a finally block. 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) executes to normal completion. Statements that cause the finally block to complete abruptly also cause the try block to complete abruptly and consequently suppress any exception thrown from the try or catch blocks. According to the Java Language Specification, §14.20.2, Execution of try-catch-finally [JLS 2005]:

If execution of the try block completes abruptly for any other 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).

...

MITRE CWE

CWE-459. Incomplete cleanup

 

CWE-584. Return inside finally block

Bibliography

[Bloch 2005]

Puzzle 36. Indecision

[Chess 2007]

8.2, Managing Exceptions, The Vanishing Exception

[JLS 2005]

§14.20.2, Execution of try-catch-finally

...