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

...

Code Block
bgColor#FFCCCC
public class Operation {
  privatepublic 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.

...

Code Block
bgColor#ccccff
public class Operation {
  public 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.

...

Code Block
bgColor#ccccff
public class Operation {
  public 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(BufferredReaderCloseable sc) {
    if (sc != null) {
      try {
        sc.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)

...

Code Block
bgColor#ccccff
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 Handleto exceptionhandler
    }
  }

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

...

<ac:structured-macro ac:name="unmigrated-wiki-markup" ac:schema-version="1" ac:macro-id="874cff7d90a2b3bb-16362325-49734bc4-b771a57f-d1b3cc51289f2f2ecbfd5557"><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="ce9ca6fe6e5b9806-0594ee64-4544469f-b177a2dd-33c0d5df6f9f67bf7164b286"><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="286e64f393492f57-4cdd66bf-4bd84dae-bfbb81bd-1ef3e81c1c59c8c229e8226f"><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="3d8d8de7ac050ab9-efbd0d20-412a4d8e-87dfad32-8bf5d62cb8ec42864641aa96"><ac:plain-text-body><![CDATA[

[[J2SE 2011

AA. Bibliography#J2SE 11]]

The try-with-resources Statement

]]></ac:plain-text-body></ac:structured-macro>

...