Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: Parasoft Jtest 2021.1

Methods invoked from within a finally block can throw an exception. Failure to catch and handle such exceptions results in the abrupt termination of the entire try block. Abrupt termination causes any exception thrown in the try block to be lost, preventing any possible recovery method from handling that specific problem. Additionally, the transfer of control associated with the exception may prevent execution of any expressions or statements that occur after the point in the finally block from which the exception is thrown. Consequently, programs must appropriately handle checked exceptions that are thrown from within a finally block.

Allowing checked exceptions to escape a finally block also violates ERR04-J. Do not complete abruptly from a finally blockIt is possible that an exception gets thrown in the finally block even though it escapes detection at compile time. This can prevent other clean-up statements from getting executed.

Noncompliant Code Example

The finally clause This noncompliant code example contains a finally block that closes the reader object in this noncompliant example. However, it is incorrectly assumed . The programmer incorrectly assumes that the statements within in the finally block cannot throw exceptions . Notably, close() can throw an IOException which in turn prevents any subsequent clean-up lines from getting executed. This is not detected at compile time since close() throws the same exception type as read or writeand consequently fails to appropriately handle any exception that may arise.

Code Block
bgColor#FFCCCC

public class LoginOperation {
  public static void checkPassworddoOperation(String passwordsome_file) throws IOException {
  
  // ... StringBufferCode fileDatato =check new StringBuffer(1000);
    BufferedReader reader = new BufferedReader(new FileReader(password_file));

or set character encoding ...
    try {
      BufferedReader    int n;reader =
          char[] passwd = new char[1024];
          while ((n = reader.read(passwd)) >= 0) {
            String readData = String.valueOf(passwd, 0, nnew BufferedReader(new FileReader(some_file));
            fileData.append(readData);try {
        // Do   passwd = new char[1024];
  operations 
        }
          String realPassword = "javac<at:var at:name="f3b" />b3";finally {
          System.out.println(fileData.toString()reader.close();
        
          if (fileData.toString().equals(realPassword)) {
            System.out.println("Login successful");
   // ... Other cleanup code ...
       }
          else {
            System.out.println("Login failed");
          }
    } finally {
      reader.close();} catch (IOException x) {
      //other clean-upForward codeto handler
    }
  }

  public static void main(String[] args) throws IOException {
    String path = "c:\\password.txt";
    checkPassword(path);
  }
}

Compliant Solution

}

The close() method can throw an IOException, which, if thrown, would prevent execution of any subsequent cleanup statements. This problem will not be diagnosed by the compiler because any IOException would be caught by the outer catch block. Also, an exception thrown from the close() operation can mask any exception that gets thrown during execution of the Do operations block, preventing proper recovery.

Compliant Solution (Handle Exceptions in finally Block)

This compliant solution encloses the close() method invocation in a try-catch block of its own within the finally block. Consequently, the potential IOException can be handled without allowing it to propagate This compliant solution correctly places the close() statement in a try-catch block. As a result an IOException can be handled without letting it propagate any further.

Code Block
bgColor#ccccff

public class LoginOperation {
  public static void checkPassworddoOperation(String passwordsome_file) throws IOException {
  
  // ... StringBufferCode fileDatato =check new StringBuffer(1000);
    BufferedReader reader = new BufferedReader(new FileReader(password_file));

or set character encoding ...
    try {
      BufferedReader    int n;
   reader =
       char[] passwd = new char[1024];
          while ((n = reader.read(passwd)) >= 0) {
            String readData = String.valueOf(passwd, 0, n)BufferedReader(new FileReader(some_file));
            fileData.append(readData);try {
        // Do   passwd = new char[1024];operations 
          }
          String realPassword = "javac<at:var at:name="f3b" />b3";finally {
          System.out.println(fileData.toString());
        
          if (fileData.toString().equals(realPassword)) try {
            System.out.println("Login successful"reader.close();
          }
 catch (IOException        else ie) {
          //  System.out.println("Login failed");
 Forward to handler
         }
    } finally {
      try {     //enclose in try-catch block
        reader.close();... Other cleanup code ...
        //other clean-up code }
     } }catch (IOException iex) {ie.getMessage();}
    }
}

  public// staticForward void main(String[] args) throws IOException {to handler
    String path = "c:\\password.txt";
    checkPassword(path);}
  }
}

Compliant Solution

...

(try-with-resources)

Java SE 7 introduced a feature called try-with-resources that can close certain resources automatically in the event of an error. This compliant solution uses try-with-resources to properly close the fileIf the need to close a stream without throwing an exception occurs often, then an alternative solution to wrapping every call of close() in its own try-catch block is to write a method, as shown in this compliant solution.

Code Block
bgColor#ccccff

public class LoginOperation {
  public static void checkPassworddoOperation(String passwordsome_file) throws IOException {
  
  // ... StringBufferCode fileDatato =check new StringBuffer(1000);
    BufferedReader reader = new BufferedReader(new FileReader(password_file));

    try {or set character encoding ...
    try ( // try-with-resources
      BufferedReader    int n;reader =
          char[] passwd = new char[1024];
          while ((n = reader.read(passwd)) >= 0new BufferedReader(new FileReader(some_file))) {
      // Do operations
    String} readData = String.valueOf(passwd, 0, n);catch (IOException ex) {
      System.err.println("thrown exception: " +   fileDataex.appendtoString(readData));
            passwd = new char[1024];
          }
          String realPassword = "javac<at:var at:name="f3b" />b3";
          System.out.println(fileData.toString())Throwable[] suppressed = ex.getSuppressed();
      for (int 
i = 0; i <      if (fileData.toString().equals(realPassword))suppressed.length; i++) {
            System.outerr.println("Loginsuppressed exception: successful");
          }
          else {
            System.out.println("Login failed"+ suppressed[i].toString());
          }
    } finally {
          closeIgnoringException(reader);
          //other clean-upForward codeto handler
    }
  }

  privatepublic static void closeIgnoringExceptionmain(CloseableString[] sargs) {
    if (s != nullargs.length < 1) {
      try {
        s.close();
      } catch (IOException ie) {System.out.println("Please supply a path as an argument");
        // Ignore exception if close fails
 return;
     }
    }
  }

  public static void main(String[] args) throws IOException {
    String path = "c:\\password.txt"doOperation(args[0]);
    checkPassword(path);
  }
}

When an IOException occurs in the try block of the doOperation() method, it is caught by the catch block and printed as the thrown exception. Exceptions that occur while creating the BufferedReader are included. When an IOException occurs while closing the reader, that exception is also caught by the catch block and printed as the thrown exception. If both the try block and closing the reader throw an IOException, the catch clause catches both exceptions and prints the try block exception as the thrown exception. The close exception is suppressed and printed as the suppressed exception. In all cases, the reader is safely closed.

Risk Assessment

Failing Failure to handle an exception in a finally block can lead to may have unexpected results.

Rule

Severity

Likelihood

Remediation Cost

Priority

Level

EXC31

ERR05-J

low

Low

unlikely

Unlikely

medium

Medium

P2

L3

Automated Detection

...

TODO

Related Vulnerabilities

Search for vulnerabilities resulting from the violation of this rule on the CERT website.

References

Wiki Markup
\[[Bloch 05|AA. Java References#Bloch 05]\] Puzzle 41: Field and Stream
\[[Harold 99|AA. Java References#Harold 99]\]
\[[Chess 07|AA. Java References#Chess 07]\] 8.3 Preventing Resource Leaks (Java)

Tool
Version
Checker
Description
Coverity7.5PW.ABNORMAL_TERMINATION_ OF_FINALLY_BLOCKImplemented
Parasoft Jtest
Include Page
Parasoft_V
Parasoft_V
CERT.ERR05.ARCF
CERT.ERR05.ATSF
Avoid using 'return's inside 'finally blocks if thare are other 'return's inside the try-catch block
Do not exit "finally" blocks abruptly
SonarQube
Include Page
SonarQube_V
SonarQube_V
S1163Exceptions should not be thrown in finally blocks

Related Guidelines

MITRE CWE

CWE-248, Uncaught Exception 

CWE-460, Improper Cleanup on Thrown Exception 

CWE-584, Return inside finally Block 

CWE-705, Incorrect Control Flow Scoping

CWE-754, Improper Check for Unusual or Exceptional Conditions 

Bibliography

[Bloch 2005]

Puzzle 41, "Field and Stream"

[Chess 2007]

Section 8.3, "Preventing Resource Leaks (Java)"

[Harold 1999]


[J2SE 2011]

The try-with-resources Statement


...

Image Added Image Added Image AddedEXC30-J. Do not exit abruptly from a finally block      10. Exceptional Behavior (EXC)      11. Miscellaneous (MSC)