You are viewing an old version of this page. View the current version.

Compare with Current View Page History

« Previous Version 80 Next »

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 causes any exception thrown in the try block to be forgotten, 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 exit 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.

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

The close() method can throw an IOException which, if thrown, would prevent execution of any subsequent clean-up statements. The compiler will correctly fail to diagnose this problem because IOException}}s are caught by the outer catch block. Also, an exception thrown from the {{close() operation can also mask any exception that gets thrown during the Do operations section, 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 it to propagate farther.

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

Compliant Solution (Java 1.7: try-with-resources)

Java 1.7 provides a new 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 file.

public class Operation {
  public static void doOperation(String some_file) {
    // ... code to check or set character encoding ...
    try (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());
      }
      // Forward to handler
    }
  }

  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 caught by the catch block and be printed as the thrown exception. This includes both any exceptions while doing operations and also any exceptions incurred while creating the BufferedReader. When an IOException occurs while closing the reader, that exception will also be caught by the catch block and will be printed as the thrown exception. When both the try block and also 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 can lead to unexpected results.

Recommendation

Severity

Likelihood

Remediation Cost

Priority

Level

ERR05-J

low

unlikely

medium

P2

L3

Related Guidelines

MITRE CWE

CWE ID 460, "Improper Cleanup on Thrown Exception"

 

CWE ID 584, "Return Inside Finally Block"

 

CWE ID 248, "Uncaught Exception"

 

CWE ID 705, "Incorrect Control Flow Scoping"

Bibliography

<ac:structured-macro ac:name="unmigrated-wiki-markup" ac:schema-version="1" ac:macro-id="14b48160-4fd1-40fc-ab4e-5b11b09e21a3"><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="ddbb650d-6740-4152-9cb4-7078f0f48c8f"><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="fb0e56dd-318b-4ac0-8d5e-ab2889f3a73a"><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="2edbbade-842e-4b4a-96c9-9c9b3561561b"><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 let code throw undeclared checked exceptions

  • No labels