Java try-finally return design question

后端 未结 7 2373
滥情空心
滥情空心 2020-11-27 04:04

In Java, a try { ... } finally { ... } is executed somewhat unintuitively to me. As illustrated in another question, Does finally always execute in Java?, if you have a retu

7条回答
  •  情书的邮戳
    2020-11-27 04:16

    Though The finally block is made for closing resources, and a return statement is generally not supposed to be there, and Eclipse warns that "finally block does not complete normally", I found in some circumstances a "finally return" is still desirable.

    ResponseType response = new ResponseType();
    try{
        //set some properties of the response object.
        response.setStatus(1);
        //return response;
    }catch (Exception e){
        //Some other properties of the response object according to the exception.
        response.setStatus(0);
        //return response;
    }finally{
        return response;
    }
    

    If I don't put the return clause in the finally block, I would have to repeat it in try and catch blocks and the current code is a little clearer.

提交回复
热议问题