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

Compare with Current View Page History

« Previous Version 69 Next »

Methods invoked from within a finally block can throw an exception. Failing 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 statement that occurs after the point in the finally block from which the exception is thrown. Consequently, programs must handle checked exceptions appropriately 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 handle the exception appropriately.

public class Operation {
  private static void doOperation(String some_file) throws IOException {
    BufferedReader reader = null;
    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 not 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, an IOException can be handled without permitting it to propagate farther.

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

    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 does not affect future program behavior.

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 to use a closeHandlingException() method, as shown in this compliant solution.

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

    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 should an error occur. This compliant solution uses try-with-resources to properly close the file.

public class Operation {
  static void doOperation(String some_file) {
    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]);
  }
}

If 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 any error while doing operations as well as any error incurred while creating the BufferedReader. If an IOException occurs while closing the reader, that error will also be caught by the catch block and be printed as the thrown exception. If IOException}}s occur in both the try block and while closing the {{reader, the catch clause still catches both, 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.

For this program not to violate ERR00-J. Do not suppress or ignore checked exceptions, appropriate error handling must be added.

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

[[Bloch 2005]] Puzzle 41: Field and Stream
[[Chess 2007]] 8.3 Preventing Resource Leaks (Java)
[[Harold 1999]]
[[J2SE 2011]] The try-with-resources Statement


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