问题
有没有一种优雅的方法来处理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
块中的try
/catch
?
#1 热门回答(71 赞)
我通常这样做:
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 );
}
}
#2 热门回答(25 赞)
我通常在org.apache.commons.io.IOUtils
中使用53430842方法中的一个:
public static void closeQuietly(OutputStream output) {
try {
if (output != null) {
output.close();
}
} catch (IOException ioe) {
// ignore
}
}
#3 热门回答(21 赞)
如果你使用的是Java 7和resource
implementsAutoClosable
,则可以执行此操作(使用InputStream作为示例):
try (InputStream resource = getInputStream()) {
// Use the resource.
}
catch( Exception ex ) {
// Problem with the resource.
}