try {
} catch() {}
finally {
try {
} catch() { }
finally { }
}
Run Code Online (Sandbox Code Playgroud)
拥有上面的代码是好的吗?
Viv*_*sse 31
是的,你可以这样做.
实际上,在处理要正确关闭的流时,甚至需要执行此操作:
InputStream in = /* ... */;
try {
} catch (...) {
} finally {
try {
in.close();
} catch (...) {
} finally {
}
}
Run Code Online (Sandbox Code Playgroud)
我认为这不是一种不好的做法
Sur*_*ran 10
为了便于阅读,您可以将嵌套的try-catch分解为单独的方法,例如:
try{
}catch(){}
finally{
cleanup();
}
Run Code Online (Sandbox Code Playgroud)
第二个try-catch可以在清理方法中.
为了支持IO包中的上述模式,JAVA6引入了一个名为Closeable的新类,所有流都实现了,因此您可以使用以下单个清理方法:
public static boolean cleanup(Closeable stream)
{
try{
stream.close();
return true;
}catch(){
return false;
}
}
Run Code Online (Sandbox Code Playgroud)