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. This Abrupt termination causes any exception thrown in the try block to be forgottenlost, 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 arise.

Code Block
bgColor#FFCCCC

public class Operation {
  privatepublic static void doOperation(String some_file) throws IOException {
    BufferedReader reader = null;
    // ... codeCode to check or set character encoding ...
    try {
      BufferedReader reader =
          new BufferedReader(new FileReader(some_file));
      // Do operations 
try {
       } finally// {
Do operations 
    if (reader !=} null)finally {
        reader.close();
      }
      // ... Other clean-upcleanup code ...
    }
  }

   public static} voidcatch main(String[]IOException argsx) throws{
 IOException {
    String// pathForward = "somepath";to handler
    doOperation(path);}
  }
}

The close() method can throw an IOException, which, if thrown, would prevent execution of any subsequent clean-up cleanup statements. The compiler will correctly fail to diagnose this problem because the doOperation() method explicitly declares that it may throw IOExceptionThis 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 permitting allowing it to propagate fartherfurther.

Code Block
bgColor#ccccff

public class Operation {
  public static void doOperation(String some_file) throws IOException {
    BufferedReader reader = null;
    // ... codeCode to check or set character encoding ...
    try {
      BufferedReader reader =
          new BufferedReader(new FileReader(some_file));
      // Do operations
    } finally {
try {
        // if (reader != null) {Do operations 
      }  tryfinally {    
          // Enclose in try-catch block{
          reader.close();
        } catch (IOException ie) {
          // Forward to handler
        }
      }
      // Other clean-up code
    }
  }

  public static void main(String[] args) throws IOException {
    String path = "somepath";
    doOperation(path);
  }
}

...

.

...

.

...

Compliant Solution (Dedicated Method to Handle Exceptions)

...

.

...

Code Block
bgColor#ccccff

public class Operation {
  static void doOperation(String some_file) throws IOException {
    BufferedReader reader = null;
    // ... code to check or set character encoding ...
    try {
      reader = new BufferedReader(new FileReader(some_file));
      // Do operations
    } finally {
      closeHandlingException(reader);
      // Other clean-up code  Other cleanup code ...
    }
  } 

  private static void closeHandlingException(BufferredReader s) {
    if (s != null) {
      try {
        s.close();
      } catch (IOException iex) {
        // Forward to handler
      }
    }
  }

  public static void main(String[] args) throws IOException {
    doOperation("somepath");
  }
}

Compliant Solution (

...

try-with-resources)

Java 1.SE 7 provides introduced a new feature , called try-with-resources, that  that can close certain resources automatically in the event of an error. This compliant solution uses try-with-resources to properly close the file.

Code Block
bgColor#ccccff

public class Operation {
  public static void doOperation(String some_file) {
    // ... codeCode to check or set character encoding ...
    try ( // try-with-resources
      BufferedReader reader =
          new BufferedReader(new FileReader(some_file))) {
      // Do operations
    } catch (IOException ex) {
      System.err.println("thrown exception: " + ex.toString());
      Throwable[] suppressed = ex.getSuppressed();
      for (int i = 0; i < suppressed.length; i++) {
        System.err.println("suppressed exception: " 
            + suppressed[i].toString());
      }
      // HandleForward to exceptionhandler
    }
  }

  public static void main(String[] args) {
    if (args.length < 1) {
      System.out.println("Please supply a path as an argument");
      return;
    }
    doOperation(args[0]);
  }
}

When an IOException occurs in the try block of the doOperation() method, it will be is caught by the catch block and be printed as the thrown exception. This includes both any error while doing operations and also any error incurred while Exceptions that occur while creating the BufferedReader are included. When an IOException occurs while closing the reader, that error will exception is also be caught by the catch block and will be printed as the thrown exception. When If both the try block and also closing the reader throw an IOException, the catch clause catches both exceptions , and prints the try- block error exception as the thrown exception. The close error exception is suppressed and printed as the suppressed exception. In all cases, the reader is safely closed.This example as written violates ERR00-J. Do not suppress or ignore checked exceptions; the appropriate error handling required for compliance has been elided for clarity.

Risk Assessment

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

Recommendation

Rule

Severity

Likelihood

Remediation Cost

Priority

Level

ERR05-J

low

Low

unlikely

Unlikely

medium

Medium

P2

L3

Related Vulnerabilities

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

Bibliography

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

<ac:structured-macro ac:name="unmigrated-wiki-markup" ac:schema-version="1" ac:macro-id="930f55e9-8067-4df2-ba32-e5b2b8fc1233"><ac:plain-text-body><![CDATA[

[[Bloch 2005

AA. Bibliography#Bloch 05]]

Puzzle 41: Field and Stream

]]></ac:plain-text-body></ac:structured-macro>

<ac:structured-macro ac:name="unmigrated-wiki-markup" ac:schema-version="1" ac:macro-id="3a0b7ee7-4c65-44fd-b9a1-0f63aa95c2a9"><ac:plain-text-body><![CDATA[

[[Chess 2007

AA. Bibliography#Chess 07]]

8.3 Preventing Resource Leaks (Java)

]]></ac:plain-text-body></ac:structured-macro>

<ac:structured-macro ac:name="unmigrated-wiki-markup" ac:schema-version="1" ac:macro-id="3f35d679-02b9-45d8-8068-55413442b888"><ac:plain-text-body><![CDATA[

[[Harold 1999

AA. Bibliography#Harold 99]]

 

]]></ac:plain-text-body></ac:structured-macro>

<ac:structured-macro ac:name="unmigrated-wiki-markup" ac:schema-version="1" ac:macro-id="0de23a46-b83a-4c03-a71b-5e05f7a55e5d"><ac:plain-text-body><![CDATA[

[[J2SE 2011

AA. Bibliography#J2SE 11]

]

The try-with-resources Statement

]]></ac:plain-text-body></ac:structured-macro>


...

ERR04-J. Do not exit abruptly from a finally block      06. Exceptional Behavior (ERR)      ERR06-J. Do not allow exceptions to expose sensitive informationImage Added Image Added Image Added