Versions Compared

Key

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

It is possible that an exception gets 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 finally block even though it escapes detection at compile time. This can prevent other clean-up statements from getting executed.

Non-Compliant Code Example

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 block.

Noncompliant Code Example

This noncompliant code example contains a finally block that closes the reader object. The programmer incorrectly assumes that the statements in the finally block cannot throw exceptions and consequently fails to appropriately handle any exception that may ariseThe finally clause closes the reader object in this non-compliant example. However, it is incorrectly assumed that the statements within 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 write.

Code Block
bgColor#FFCCCC

public class LoginOperation {
  public static void checkPassworddoOperation(String passwordsome_file) throws IOException {
  
    StringBuffer fileData = new StringBuffer(1000);
{
    // ... Code to check or set character encoding ...
    try {
      BufferedReader reader =
          new BufferedReader(new FileReader(passwordsome_file));

      try {
        // Do intoperations n;
      } finally {
  char[]   passwd = new char[1024] reader.close();
        // ... whileOther ((ncleanup =code reader.read(passwd)) >= 0) {...
      }
    } catch String(IOException readDatax) = String.valueOf(passwd, 0, n);
{
      // Forward to handler
      fileData}
  }
}

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 further.

Code Block
bgColor#ccccff
public class Operation {
  public static void doOperation(String some_file) {
    // ... Code to check or set character encoding ...
    try {
      BufferedReader reader =
 .append(readData);
            passwd = new char[1024];
          }
          String realPassword = "javac<at:var at:name="f3b" />b3";
         new System.out.println(fileData.toString(BufferedReader(new FileReader(some_file));
      try {
 
       // Do operations if (fileData.toString().equals(realPassword)) {
    
      } finally {
        System.out.println("Login successful");try {
          }reader.close();
        } catch else(IOException ie) {
          //  System.out.println("Login failed");
 Forward to handler
         }
    }  finally {
 // ... Other cleanup code reader.close();...
      //other clean-up code }
    }
}

 catch public static void main(String[] args) throws IOException {
(IOException x) {
      String// pathForward = "c:\\password.txt";to handler
    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 correctly places the close() statement in a try-catch block. Thus an IOException can be handled without letting it propagate any furtheruses try-with-resources to properly close the file.

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)) >= 0BufferedReader(new FileReader(some_file))) {
      // Do operations
    String} readDatacatch = String.valueOf(passwd, 0, n);(IOException ex) {
      System.err.println("thrown exception: " +   fileDataex.appendtoString(readData));
      Throwable[] suppressed     passwd = new char[1024]= ex.getSuppressed();
      for (int i = }
0; i < suppressed.length;       String realPassword = "javac<at:var at:name="f3b" />b3";i++) {
          System.outerr.println(fileData.toString());
   "suppressed exception: " 
     
          if (fileData+ suppressed[i].toString().equals(realPassword)) {
            System.out.println("Login successful");
          }
      // Forward to  else {handler
            System.out.println("Login failed");
        }
  }
    } finally {
  public static void  trymain(String[] args) {
     //enclose in try-catch blockif (args.length < 1) {
        reader.close();
        //other clean-up code System.out.println("Please supply a path as an argument");
      }catch (IOException ie) {ie.getMessage()}return;
    }
}

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

References

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

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

Rule

Severity

Likelihood

Remediation Cost

Priority

Level

ERR05-J

Low

Unlikely

Medium

P2

L3

Automated Detection

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 AddedJava Puzzlers 5.41
Java I/O