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

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

    I use try/finally in the following form :

    try{
       Connection connection = ConnectionManager.openConnection();
       try{
           //work with the connection;
       }finally{
           if(connection != null){
              connection.close();           
           }
       }
    }catch(ConnectionException connectionException){
       //handle connection exception;
    }
    

    I prefer this to the try/catch/finally (+ nested try/catch in the finally). I think that it is more concise and I don't duplicate the catch(Exception).

提交回复
热议问题