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

Compare with Current View Page History

« Previous Version 49 Next »

Code inside a finally block can throw an exception. Programmers often fail to catch and handle such exceptions. This can be problematic for several reasons. An exception thrown in a finally block becomes the reason for abrupt termination of the entire try block, potentially masking an exception thrown in the try block. Further, the transfer of control associated with the exception prevents execution of any clean-up statements that follow the statement from which the exception is thrown. Consequently, programs must appropriately handle checked exceptions thrown from within a finally block.

Noncompliant Code Example

This noncompliant code example uses 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 handle the exception appropriately.

public class Operation {
  private static void doOperation(String some_file) throws IOException {
    BufferedReader reader = new BufferedReader(new FileReader(some_file));
    // Do operations 
     
    } finally {
      reader.close();
      // ... Other clean-up code ...
    }
  }

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

The close() method could throw an IOException, which would prevent execution of any subsequent clean-up statements. This possibility remains undiagnosed at compile time because the close() method's throws clause specifies the same exceptions as do the throws clauses of methods read() and write().

Compliant Solution (Handle Exceptions in finally Block)

This compliant solution correctly places the close() statement in a try-catch block of its own. Consequently, an IOException can be handled without permitting it to propagate farther.

public class Operation {
  static void doOperation(String some_file) throws IOException {
    BufferedReader reader = new BufferedReader(new FileReader(some_file));

    try {
      // Do operations
    } finally {
      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);
  }
}

Compliant Solution (2) (Dedicated Method to Handle Exceptions)

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

public class Operation {
  static void doOperation(String some_file) throws IOException {
    BufferedReader reader = new BufferedReader(new FileReader(some_file));

    try {
      // Do operations
    } finally {
      closeHandlingException(reader);
      // Other clean-up code 
    }
  } 

  private static void closeHandlingException(BufferredReader s) {
    if (s != null) {
      try {
        s.close();
      } catch (IOException ie) {
        // Ignore exception if close fails
      }
    }
  }

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

Risk Assessment

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

Guideline

Severity

Likelihood

Remediation Cost

Priority

Level

EXC05-J

low

unlikely

medium

P2

L3

Related Vulnerabilities

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

Bibliography

[[Bloch 2005]] Puzzle 41: Field and Stream
[[Harold 1999]]
[[Chess 2007]] 8.3 Preventing Resource Leaks (Java)


ERR04-J. Do not exit abruptly from a finally block      06. Exceptional Behavior (EXC)      EXC06-J. Do not allow exceptions to expose sensitive information

  • No labels