throws Exception in finally blocks

后端 未结 15 2348
慢半拍i
慢半拍i 2020-11-29 18:04

Is there an elegant way to handle exceptions that are thrown in finally block?

For example:

try {
  // Use the resource.
}
catch( Excep         


        
15条回答
  •  暗喜
    暗喜 (楼主)
    2020-11-29 18:34

    I usually do this:

    MyResource r = null;
    try { 
       // use resource
    } finally {   
        if( r != null ) try { 
            r.close(); 
        } catch( ThatSpecificExceptionOnClose teoc ){}
    }
    

    Rationale: If I'm done with the resource and the only problem I have is closing it, there is not much I can do about it. It doesn't make sense either to kill the whole thread if I'm done with the resource anyway.

    This is one of the cases when at least for me, it is safe to ignore that checked exception.

    To this day I haven't had any problem using this idiom.

提交回复
热议问题