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

Compare with Current View Page History

« Previous Version 71 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.

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 {
  private 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 {
      if (reader != null) {
        reader.close();
      }
      // ... Other clean-up code ...
    }
  }

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

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 the doOperation() method explicitly declares that it may throw IOException.

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 {
  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 {
      if (reader != null) {
        try {    
          // 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);
  }
}

While ignoring a caught exception normally violates ERR00-J. Do not suppress or ignore checked exceptions, this particular code is permitted under ERR00-EX0, as the reader is never accessed again, so an error in closing it leaves future program behavior unchanged.

Compliant Solution (Dedicated Method to Handle Exceptions)

When closing a stream without throwing an exception is a frequent pattern in the code, an alternative solution is use of a closeHandlingException() method, as shown in this compliant solution.

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 
    }
  } 

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

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

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 {
  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());
      }
      // Handle exception
    }
  }

  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 error while doing operations and also any error incurred while creating the BufferedReader. When an IOException occurs while closing the reader, that error 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 error as the thrown exception. The close error 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 unexpected results.

Recommendation

Severity

Likelihood

Remediation Cost

Priority

Level

ERR05-J

low

unlikely

medium

P2

L3

Related Vulnerabilities

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

Bibliography

<ac:structured-macro ac:name="unmigrated-wiki-markup" ac:schema-version="1" ac:macro-id="4bb02e42-d795-43b0-ac9b-06a2b5cfefc1"><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="72262c87-0219-4196-8eb5-9b5b8e99f24a"><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="d9dd1346-2b0a-4095-9ebe-62672b68dfd1"><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="e9c665b7-6921-4f4c-94cd-fe63709a33da"><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 information

  • No labels