我经常写出以下这样的代码:
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();
}
}
}
通常涉及到一个会抛出异常并需要关闭的对象,而关闭它也可能会抛出异常。
我在想上面的代码是否可以简化或以任何方式重用。