throws Exception in finally blocks

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

    try {
        final Resource resource = acquire();
        try {
            use(resource);
        } finally {
            resource.release();
        }
    } catch (ResourceException exx) {
        ... sensible code ...
    }
    

    Job done. No null tests. Single catch, include acquire and release exceptions. Of course you can use the Execute Around idiom and only have to write it once for each resource type.

提交回复
热议问题