如果try中有return ,那么finally执行在return 之前还是之后?

解决方案 »

  1.   

    http://topic.csdn.net/u/20090305/20/58898020-D677-4F58-BE77-B73E978026AF.html
    根据java规范:在try-catch-finally中,如果try-finally或者catch-finally中都有return,则两个return语句都执行并且最终返回到调用者那里的是finally中return的值;而如果finally中没有return,则理所当然的返回的是try或者catch中return的值,但是finally中的代码是必须要执行的。
      

  2.   

    这个有点复杂,不过方法真正返回应该是在finally执行完后才返回的
    Core Java有一段这样说的:
    CAUTION: A finally clause can yield unexpected results when it contains return statements.
    Suppose you exit the middle of a try block with a return statement. Before the method returns,
    the contents of the finally block are executed. If the finally block also contains a return statement,
    then it masks the original return value. Consider this contrived example:
    public static int f(int n)
    {
    try
    {
    int r = n * n;
    return r;
    }
    finally
    {
    if (n == 2) return 0;
    }
    }
    If you call f(2), then the try block computes r = 4 and executes the return statement. However,
    the finally clause is executed before the method actually returns. The finally clause
    causes the method to return 0, ignoring the original return value of 4.
    这说明try clause中想返回的值被覆盖了
      

  3.   

    肯定执行,先执行finally中的输出语句,在执行返回值,但是finally中的return覆盖了try中的return!!!