Understanding try catch finally with return and value that it returns

前端 未结 3 1995
一个人的身影
一个人的身影 2020-12-29 15:29

I have the following piece of code.

public static void main(String[] args) {
    System.out.println(returnString());
}
private static String returnString(){
         


        
3条回答
  •  温柔的废话
    2020-12-29 15:52

    In Java, the code:

    try {
      if (foo()) return 1;
    } catch (Exception e){
      if (goo()) return 2;
    } finally {
      if (moo()) return 3;
    }
    

    will rewritten by the compiler into:

    try {
      if (foo())
      {
        if (moo()) return 3;  // Finally code executed before return
        return 1;
      }
    } catch (Exception e){
      if (goo())
      {
        if (moo()) return 3;  // Finally code executed before return
        return 2;
      }
    } catch (Throwable e){
      if (moo()) return 3;   // Finally code executed before re-throw
      throw e;
    }
    if (moo()) return 3;    // Finally code executed before leaving block
    

    Basically, the compiler will duplicate the code in the finally block exactly once in every execution path that would cause code execution to leave the guarded block, whether via return, throw, or fall-through. Note that while some languages disallow a return within a finally block, Java does not; if a finally block is executed as a consequence of an exception, however, a return within the block may cause the exception to get silently abandoned (look at the code above marked "Finally code executed before re-throw"; if the return 3; executes, the re-throw will get skipped).

提交回复
热议问题