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) 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 2005).

Never use return, break, continue or throw statements within a finally block.

Noncompliant Code Example

In this noncompliant code example, the finally block completes abruptly due to because of a return statement in the finally block.

Code Block
bgColor#FFCCCC
class TryFinally {              
  private static boolean doLogic() {
    try {
      throw new IllegalStateException(); 
    } finally {
      System.out.println("Uncaught Exception");
      return true;
    }
  }

  public static void main(String[] args) {
    doLogic();	
  }
}

Consequently, when When the IllegalStateException is thrown, it does not propagate all the way up through the call stack. Rather, the abrupt termination of the finally block suppresses the IllegalStateException because it the return statement becomes the final cause of abrupt termination of the try block.

...