Java Reference
In-Depth Information
try {
br.close();
} catch (IOException x) {
// Handle error
} finally {
if (bw != null) {
try {
bw.close();
} catch (IOException x) {
// Handle error
}
}
}
}
}
}
Compliant Solution ( try -with-resources)
This compliant solution uses a try -with-resources statement to manage both br and bw :
Click here to view code image
public void processFile(String inPath, String outPath)
throws IOException{
try (BufferedReader br =
new BufferedReader(new FileReader(inPath));
BufferedWriter bw =
new BufferedWriter(new FileWriter(outPath));) {
// Process the input and produce the output
} catch (IOException ex) {
// Print out all exceptions, including suppressed ones
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());
}
}
}
Thissolutionpreservesanyexceptionsthrownduringtheprocessingoftheinputwhile
still guaranteeing that both br and bw are properly closed, regardless of what exceptions
Search WWH ::




Custom Search