开发者

Putting try catch finally block inside another finally block

 try {
 } catch() {}
 finally {
     try {
     } catch() { }
     final开发者_如何学JAVAly { }
 }

Is it good to have the code like above?


Yes, you can do this.

Actually, you are even required to do it when dealing with streams you want to close properly:

InputStream in = /* ... */;
try {
} catch (...) {
} finally {
    try {
        in.close();
    } catch (...) {
    } finally {
    }
}

I don't see any case in which this would be a bad practice


For readability you can factor out the nested try-catch in to a separate method, like:

  try{
  }catch(){}
  finally{
    cleanup();
  }

And the second try-catch can be inside the cleanup method.

To support the above pattern in IO package, JAVA6 introduces a new class called Closeable that all streams implement, so that you can have a single cleanup method as follows:

public static boolean cleanup(Closeable stream)
{
try{
    stream.close();
    return true;
  }catch(){
    return false;
  }
}


It is best to avoid it when you can, but sometimes it may be necessary. If you tell us more about why you think you need this, we may be able to give better answers :-)

One reason to think about may be to commit a transaction in the finally block, when the commit operation itself may throw an exception.

It is important to note that exceptions thrown inside a finally block may easily shadow exceptions thrown earlier, within the try block, unless handled properly. Thus such nested try/catch blocks are sometimes the way to go. However, as others have noted, to improve readability, it is advisable to extract the insides of the finally block into a separate method.


It's ugly, but there are cases where you can't avoid it, especially in resource clean up where you have dependent resources and the clean up of one resource can throw an exception.

A typical example is tidying up ResultSet, Statement and Connection objects in JDBC code. Closing the ResultSet can throw an exception, but we'd still like to continue and close the Statement and Connection


Looks ugly but sometimes it's the way to go. Depending on the code consider to extract a method with the second try-catch-finally block.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜