I want to safely close resources and than propagate an exception. So far I came up with two solutions.
Solution 1
FileObject sourceDir = null;
FileObject targetDir = null;
BufferedWriter bw = null;
BufferedReader br = null;
try {
// R/W operation with files
} finally {
// close sourceDir, targetDir, br, bw
}
Solution 2
FileObject sourceDir = null;
FileObject targetDir = null;
BufferedWriter bw = null;
BufferedReader br = null;
try {
// R/W operation with files
} catch (IOException e) {
throw e;
} finally {
// close sourceDir, targetDir, br, bw
}
I don’t like throw e in the second solution but try-finally seems a little bit unusual to me so I’m not sure which one of these I should use. Or is there any better way how to do it?
Option 1 is exacly right.
try ... finallyis usually used for that.You might even put a
returninto your try block and Java will process yourfinallyand return then.