Putting try catch finally block inside another finally block

前端 未结 5 1114
孤独总比滥情好
孤独总比滥情好 2021-02-07 00:57
 try {
 } catch() {}
 finally {
     try {
     } catch() { }
     finally { }
 }

Is it good to have the code like above?

5条回答
  •  忘了有多久
    2021-02-07 01:22

    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.

提交回复
热议问题