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

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

    Finally block will always execute even if we caught the exception in catch block or even our try block executed as expected.

    so when does finally block will be execute with in the flow...

    if we have return statement inside the try/catch block then before executing the return statement finally block will be executed (like as for closing the connection or I/O)

    function returnType process() {
      try {
          // some other statements
          // before returning someValue, finally block will be executed
          return someValue;
      } catch(Exception ex) {
         // some error logger statements
         // before returning someError, finally block will be executed
         return someError;
      } finally {
        // some connection/IO closing statements
        // if we have return inside the finally block
        // then it will override the return statement of try/catch block
        return overrideTryCatchValue;
      }
    }
    

    but if you have return statement inside the finally statement then it will override the return statement inside the try or catch block.

提交回复
热议问题