| Wiki Markup |
|---|
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 terminatecomplete abruptly also cause the {{try}} block to terminatecomplete abruptly and consequently suppress any exception thrown from the {{try}} or {{catch}} blocks \[[JLS 2005. According to the _Java Language Specification_, [§14.20.2, Execution of try-catch-finally|http://java.sun.com/docs/books/jls/third_edition/html/statements.html#14.20.2] \[[JLS 2005|AA. References#JLS 05]\]: |
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).
Noncompliant Code Example
...
The IllegalStateException is suppressed by the abrupt termination completion of the finally block caused by the return statement.
...
| Code Block | ||
|---|---|---|
| ||
class TryFinally {
private static boolean doLogic() {
try {
throw new IllegalStateException();
} finally {
int c;
try {
while ((c = input.read()) != -1) {
if (c > 128) {
break;
}
}
} catch (IOException x) {
// forward to handler
}
System.out.println("logic done");
}
// Any return statements must go here; applicable only when exception is thrown conditionally
}
}
|
Risk Assessment
Exiting Completing abruptly from a finally block masks any exceptions thrown inside the associated try and catch blocks.
...
<ac:structured-macro ac:name="unmigrated-wiki-markup" ac:schema-version="1" ac:macro-id="b9565f310596f895-92414d4b-4513405f-b800822b-0a2d2542f8b29c24b255b2f2"><ac:plain-text-body><![CDATA[ | [[Bloch 2005 | AA. References#Bloch 05]] | Puzzle 36. Indecision | ]]></ac:plain-text-body></ac:structured-macro> | |
<ac:structured-macro ac:name="unmigrated-wiki-markup" ac:schema-version="1" ac:macro-id="faa5b194fde1ad4d-1e9e0588-45104065-8527aa7c-39b838bfc4868ff5177d91a4"><ac:plain-text-body><![CDATA[ | [[Chess 2007 | AA. References#Chess 07]] | 8.2, Managing Exceptions, The Vanishing Exception | ]]></ac:plain-text-body></ac:structured-macro> | |
<ac:structured-macro ac:name="unmigrated-wiki-markup" ac:schema-version="1" ac:macro-id="0144b2eff2d1647d-74afd0be-49c046a5-9d439e1a-8ddb57d6a29c74fc3e476c87"><ac:plain-text-body><![CDATA[ | [[JLS 2005 | AA. References#JLS 05]] | [§14.20.2, Execution of try-catch-finally | http://java.sun.com/docs/books/jls/third_edition/html/statements.html#14.20.2] | ]]></ac:plain-text-body></ac:structured-macro> |
...