Is a finally block without a catch block a java anti-pattern?

前端 未结 12 676
鱼传尺愫
鱼传尺愫 2020-12-05 12:35

I just had a pretty painful troubleshooting experience in troubleshooting some code that looked like this:

try {
   doSomeStuff()
   doMore()
} finally {
            


        
12条回答
  •  南笙
    南笙 (楼主)
    2020-12-05 13:14

    In my opinion, it's more the case that finally with a catch indicate some kind of problem. The resource idiom is very simple:

    acquire
    try {
        use
    } finally {
        release
    }
    

    In Java you can have an exception from pretty much anywhere. Often the acquire throws a checked exception, the sensible way to handle that is to put a catch around the how lot. Don't try some hideous null checking.

    If you were going to be really anal you should note that there are implied priorities among exceptions. For instance ThreadDeath should clobber all, whether it comes from acquire/use/release. Handling these priorities correctly is unsightly.

    Therefore, abstract your resource handling away with the Execute Around idiom.

提交回复
热议问题