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

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

提交回复
热议问题