在Java中,在抛出异常的方法中关闭变量的正确方法是什么?
在Java中,我经常在在Java中,在抛出异常的方法中关闭变量的正确方法是什么?,java,exception-handling,Java,Exception Handling,在Java中,我经常在finally块中关闭变量,如下所示: public void someMethod(){ InputStream inStream = null; PreparedStatement pStatement = null; try{ do something here } catch(Exception ex){ do something here } finally{ try{ if (inStream != null) inStream.c
finally
块中关闭变量,如下所示:
public void someMethod(){
InputStream inStream = null;
PreparedStatement pStatement = null;
try{ do something here }
catch(Exception ex){ do something here }
finally{
try{ if (inStream != null) inStream.close(); } catch(Exception ex){/* do nothing */}
try{ if (pStatement != null) pStatement.close(); } catch(Exception ex){/* do nothing */}
}
}
我想知道,如果这个方法说它抛出了一个异常,是否有一个像“finally”这样的地方可以关闭这个方法的变量?
例如:
public void anotherMethod() throws SQLException {
// This method doesn't need a try/catch because the method throws an exception.
InputStream inStream = null;
PreparedStatement pStatement = null;
// Where can I ensure these variables are closed?
// I would prefer not to have them be global variables.
}
正确的方法实际上是使用Java7中引入的构造
public void anotherMethod() throws SQLException {
try (PreparedStatement st = connection.prepareStatement(...)) {
// do things with st
}
}
这确保无论
try
块中发生什么(成功执行或以异常结束),资源都将关闭。您不需要添加catch
部分,因为该方法抛出SQLException
,更重要的是,您不需要添加finally
子句:所有打开的资源都保证在该语句之后关闭。正确的方法实际上是使用Java 7中引入的构造
public void anotherMethod() throws SQLException {
try (PreparedStatement st = connection.prepareStatement(...)) {
// do things with st
}
}
这确保无论try
块中发生什么(成功执行或以异常结束),资源都将关闭。您不需要添加catch
部分,因为该方法抛出SQLException
,更重要的是,您不需要添加finally
子句:所有打开的资源都保证在该语句之后关闭