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

前端 未结 7 1497
北海茫月
北海茫月 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 16:59

    When using a public functions other than void functions, you should return something or your function won't.

    0 讨论(0)
  • 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")
    
    0 讨论(0)
  • 2021-02-01 17:10

    And if I have try, catch, finally I can't put return in the try block.

    You absolutely can. You just need to make sure that every control path in your method is terminated properly. By that I mean: every execution path through your method either ends in a return, or in a throw.

    For instance, the following works:

    int foo() throws Exception { … }
    
    int bar() throws Exception {
        try {
            final int i = foo();
            return i;
        } catch (Exception e) {
            System.out.println(e);
            throw e;
        } finally {
            System.out.println("finally");
        }
    }
    

    Here, you’ve got two possible execution paths:

    1. final int i = foo()
    2. either
      1. System.out.println("finally")
      2. return i
    3. or
      1. System.out.println(e)
      2. System.out.println("finally")
      3. throw e

    Path (1, 2) is taken if no exception is thrown by foo. Path (1, 3) is taken if an exception is thrown. Note how, in both cases, the finally block is executed before the method is left.

    0 讨论(0)
  • 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
    }
    
    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2021-02-01 17:22

    I think this is what you're asking:

    And if I have try, catch, finally I can't put return in the try block.

    So if you add a catch block, you can't put a return in the try block.

    The problem is that if you add a catch then control drops through and you need a return at the end of the method or it's a syntax error. I haven't tested this but I assume you could put a return in the try block, but you would also have to add one inside the catch or at then end of the method as you have now.

    0 讨论(0)
提交回复
热议问题