throws Exception in finally blocks

后端 未结 15 2325
慢半拍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:38

    After lots of consideration, I find the following code best:

    MyResource resource = null;
    try {
        resource = new MyResource();
        resource.doSomethingFancy();
        resource.close(); 
        resource = null;  
    } finally {
        closeQuietly(resource)
    }
    
    void closeQuietly(MyResource a) {
        if (a!=null)
            try {
                 a.close();
            } catch (Exception e) {
                 //ignore
            }
    }
    

    That code guarantees following:

    1. The resource is freed when the code finished
    2. Exceptions thrown when closing the resource are not consumed without processing them.
    3. The code does not try to close the resource twice, no unnecessary exception will be created.

提交回复
热议问题