这段时间读 《Core Java 2》,读到“异常处理”的章节。
书中有以下这样的“强烈建议”的异常写法,我深为认同。try {
Object mustCloseObj = new MustCloseObj();
try{
//do things
}finally{
mustCloseObj.close(); 
}
} catch (Exception e) {
// handle exception here
}他认为这种格式的代码的好处是:
1、2个try块责任分明,里面负责关闭或销毁必须处理的东西,外面负责处理异常。
2、最重要的一点是:close方法也有可能出现异常,但它也能被很好的处理,而用一个try块是做不到的。我以前也只会用try...catch...finally,没想到这么完美的写法,佩服。
如果是Delphi则为:try
obj := TMustFreeObj.Create;
try
//do things
finally
obj.Free;
end;
except
// handle exception here
end;来自:http://blog.csdn.net/DancingCalf