I tend to write code like the following a lot:
BufferedWriter w = null; // Or any other object that throws exceptions and needs to be closed
try {
w = new BufferedWriter(new FileWriter(file));
// Do something with w
} catch (IOException e) {
e.printStackTrace();
} finally {
if (w != null) {
try {
w.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
It usually involves an object that throws exceptions and needs to be closed, and that closing it may also throw an exception.
I was wondering if the above code can be simplified or reused in any way.