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

前端 未结 7 1754
北海茫月
北海茫月 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:11

    Yes, it's confusing.

    In Java, all program control paths of a non-void function must finish with a return, or throw an exception. That's the rule put nice and simply.

    But, in an abomination, Java allows you to put an extra return in a finally block, which overrides any previously encountered return:

    try {
        return foo; // This is evaluated...
    } finally {
        return bar; // ...and so is this one, and the previous `return` is discarded
    }
    

提交回复
热议问题