...
Code Block | ||
---|---|---|
| ||
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(args[0]); } 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 error IOException
occurs in the try
block of the doOperation()
method it will propagate out of the method 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 error IOException
occurs while closing the reader
, that error will propagate out of doOperation()
also be caught by the catch block and be printed as the thrown exception. If both errors occur, 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 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.
...