Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

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, suppressing . 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 prevents 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 appropriately handle checked exceptions appropriately that are thrown from within a finally block.

...

Code Block
bgColor#FFCCCC
public class Operation {
  private static void doOperation(String some_file) throws IOException {
    BufferedReader reader = null;
    try {
      reader = new BufferedReader(new FileReader(some_file));
    try {
      // 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);
  }
}

...

Code Block
bgColor#ccccff
public class Operation {
  static void doOperation(String some_file) throws IOException {
    BufferedReader reader = null;

    try {
      reader = new BufferedReader(new FileReader(some_file));

    try {
      // 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 suppressing 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.

...

Code Block
bgColor#ccccff
public class Operation {
  static void doOperation(String some_file) throws IOException {
    BufferedReader reader = null;

    try {
      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) {
        // Forward to handler
      }
    }
  }

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

...

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

...