我有所有传播异常的方法,然后我在一个地方处理,但我意识到了一些事情。
假设我有这样的方法
public void foo() throws Exception e {
Statement stmt = createStatement();
doSomething(stmt);
stmt.close();
}
我的问题是,如果 doSometing() 方法抛出异常,语句将不会关闭,但我不想在那里处理异常。 try and catch 的正确方法是只重新抛出异常并最终关闭语句吗?
最佳答案
public void foo() throws Exception e {
Statement stmt = null ;
try {
stmt = createStatement();
doSomething(stmt);
} finally {
if(stmt != null)
stmt.close();
}
}
关于java - 如何正确关闭资源?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2362686/