有没有一种优雅的方式来处理 finally
block 中抛出的异常?
例如:
try {
// Use the resource.
}
catch( Exception ex ) {
// Problem with the resource.
}
finally {
try{
resource.close();
}
catch( Exception ex ) {
// Could not close the resource?
}
}
如何避免 finally
block 中的 try
/catch
?
最佳答案
我通常这样做:
try {
// Use the resource.
} catch( Exception ex ) {
// Problem with the resource.
} finally {
// Put away the resource.
closeQuietly( resource );
}
其他地方:
protected void closeQuietly( Resource resource ) {
try {
if (resource != null) {
resource.close();
}
} catch( Exception ex ) {
log( "Exception during Resource.close()", ex );
}
}
关于java - 在 finally block 中抛出异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/481446/