Java Reference
In-Depth Information
Click here to view code image
public void processFile(String inPath, String outPath)
throws IOException{
BufferedReader br = null;
BufferedWriter bw = null;
try {
br = new BufferedReader(new FileReader(inPath));
bw = new BufferedWriter(new FileWriter(outPath));
// Process the input and produce the output
} finally {
try {
if (br != null) {
br.close();
}
if (bw != null) {
bw.close();
}
} catch (IOException x) {
// Handle error
}
}
}
However, if an exception is thrown when the BufferedReader br is closed, then the
BufferedWriter bw will not be closed.
Compliant Solution (Second finally Block)
This compliant solution uses a second finally block to guarantee that bw is properly
closed even when an exception is thrown while closing br .
Click here to view code image
public void processFile(String inPath, String outPath)
throws IOException {
BufferedReader br = null;
BufferedWriter bw = null;
try {
br = new BufferedReader(new FileReader(inPath));
bw = new BufferedWriter(new FileWriter(outPath));
// Process the input and produce the output
} finally {
if (br != null) {
Search WWH ::




Custom Search