How does return work in try, catch, finally in Java?

前端 未结 7 1795
北海茫月
北海茫月 2021-02-01 16:26

I can\'t understand exactly how return works in try, catch.

  • If I have try and finally without
7条回答
  •  忘掉有多难
    2021-02-01 17:05

    This is normal program flow when exception handling is involved. Having catch block in the code creates a case where code path can directly jump in to catch block. This defeats the mandate of having return statement in the method which returns something. It is possible that return statement may not get executed if exception occurs, hence compiler throws error. So to avoid this issue, you need at least 1 more return statement in a method.

    If you have added a return statement in try-finally block and you dont have catch block, it is ok. There is no case of abnormal code path here.

    If you have added a return statement in try block and you have catch block, then you can either add return in catch block or at the end of method.

    If you have added a return statement in try block and you have catch block and finally block, then you can either add return in catch block or at the end of method. You can also choose to add return in finally block. If you are using eclipse, it will generate a warning which can be suppressed using below above method definition -

    @SuppressWarnings("finally")
    

提交回复
热议问题