Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: Modified NCE/CS

...

Here, the finally block completes abruptly since a return statement occurs within it. As a result, when the exception is thrown in method someException, it does not show up in the outputpropagate all the way up through the call stack. This is due to the abrupt termination of the finally block that suppresses any useful exception information from being displayed in the try block by overriding it with its own message. Note that even if the try block returns some value, the finally block is executed.

Note that NullPointerException is a RuntimeException, and thus does not need to occur in a throws declaration. The throwException() function never actually throws SomeException, although it claims to via its throws declaration.

Code Block
bgColor#FFCCCC
class SomeException extends ExceptionTryFinally { 
  public SomeException(String s) { 
    super(s); 
  }
}

class TryFinally {
  private static void throwException() throws SomeException {
    throw new NullPointerException();
  }
            
  static private boolean doLogic() {
    try {
      throw new   throwExceptionIllegalStateException(); 
    } catch (SomeException se) { System.out.println("Exception thrown"); }
  
    finally {
              System.out.println("Uncaught Exception");
              return true;
    }
  }

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

...

This compliant solution removes the return statement from the finally block. Any return statements must occur after this block. In this example, the compiler will throw an error as the return statement is unreachable due to the explicit, unavoidable throwing of IllegalStateException. If the exception is thrown conditionally, the return statement can be used without any compilation errors.

Code Block
bgColor#ccccff
class SomeException extends ExceptionTryFinally { 
  public SomeException(String s) { 
    super(s); 
  }
}

class TryFinally {
  private static void throwException() throws SomeException {
    throw new NullPointerException();
  }
            
  static private void boolean doLogic() {
    try {
      throw new   throwExceptionIllegalStateException(); 
    } catch (SomeException se) { System.out.println("Exception thrown"); }
  
    finally {
              System.out.println("UncaughtCaught Exception");
    }
    // any return true; statements must go here
  }

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

...

Exiting abruptly from a finally block may have unexpected resultslead to masking of thrown exceptions.

Rule

Severity

Likelihood

Remediation Cost

Priority

Level

EXC30-J

low

probable

medium

P4

L3

...