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

前端 未结 12 670
鱼传尺愫
鱼传尺愫 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:32

    There is absolutely nothing wrong a try with a finally and no catch. Consider the following:

    InputStream in = null;
    try {
        in = new FileInputStream("file.txt");
        // Do something that causes an IOException to be thrown
    } finally {
        if (in != null) {
             try {
                 in.close();
             } catch (IOException e) {
                 // Nothing we can do.
             }
        }
    }
    

    If an exception is thrown and this code doesn't know how to deal with it then the exception should bubble up the call stack to the caller. In this case we still want to clean up the stream so I think it makes perfect sense to have a try block without a catch.

提交回复
热议问题