Versions Compared

Key

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

...

Code Block
bgColor#ccccff
public class Operation {
  static void doOperation(String some_file) throws IOException {
    try (BufferedReader reader = new BufferedReader(new FileReader(some_file))) {
      // Do operations
    }
  }

  public static void main(String[] args) {
    if (args.length < 1) {
      System.out.println("Please supply a path as an argument");
      return;
    }
    try {
      doOperation(path args[0]);
    } catch (IOException ex) {
      System.out.println("thrown exception: " + ex.toString());
      Throwable[] suppressed = ex.getSuppressed();
      for (int i = 0; i < suppressed.length; i++) {
        System.out.println("suppressed exception: " + suppressed[i].toString());
      }

      // how handle exception(s)
    }
  }
}

If an error occurs in the try block of the doOperation() method it will propagate out of the method and be printed as the thrown exception. If an error occurs while closing the reader, that error will propagate out of doOperation() and be printed as the thrown exception. If both errors occur, the try-block error will propagates out of the doOperation() and be printed as the thrown exception. The close error is suppressed and printed as the suppressed exception. In all cases the reader is safely closed.Note that this example is for illustrative purposes only. Compliant code must perform proper exception handling, rather than simply printing exceptions to the console. For more information, see ERR00-J. Do not suppress or ignore checked exceptions.

Risk Assessment

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

...