...
This compliant solution uses a try-with-resources statement which will pass on not suppress any exception exceptions thrown during the processing of the input while still guaranteeing that br
is closed.
Code Block | ||
---|---|---|
| ||
String inPath = ...; // input file path try ( BufferedReader br = new BufferedReader(new FileReader(inPath)); ) { // process the input and produce the output } 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()); } } |
If only one exception is thrown, either during opening, processing, or closing of the file, it will be printed by the "thrown exception: "
statement. If an exception is thrown during processing, and another one is thrown while trying to close the file, then the "thrown exception: "
statement will print the exception encountered while closing the file, and the "suppressed exception: "
statement will print the exception encountered during processing.
Applicability
Failing to use a try-with-resources statement when dealing with closeable resources may result in some resources not being closed, or important exceptions being masked, possibly resulting in a denial of service attack.
...