执行顺序的重点就在finally中,具体如下:

(1)、try:它里面放置可能引发异常的代码
(2)、catch:后面对应异常类型和一个代码块,用于表明该catch块用于处理这种类型的代码块,可以有多个catch块。
(3)、finally:主要用于回收在try块里打开的物力资源(如数据库连接、网络连接和磁盘文件),异常机制总是保证
finally块总是被执行。只有finally块,执行完成之后,才会回来执行try或者catch块中的return或者throw语句,如果
finally中使用了return或者throw等终止方法的语句,则就不会跳回执行,直接停止。


为了 证明上面的结论是正确的,做了如下测试:

class Lxk { 
 
    private static int testFinallyFunc() { 
        String s = null; 
        int result; 
        try { 
            s.equals("ss"); 
            result = 1;                             //不走 
            System.out.println("try " + result);    //不走 
        } catch (Exception e) { 
            result = 2; 
            System.out.println("catch " + result);  //走,且会给result赋值 
            return result;                          //不一定会return 
        } finally { 
            result = 3; 
            System.out.println("finally " + result); 
            //return result;                        //这个打开返回的就是finally中的结果 3;关闭返回的就是catch中的结果 2 
        } 
        return result;                              //这个就占个位置,打开finally的return这个返回就永远走不到了,得注释了。 
    } 
 
    public static void main(String[] a) throws Exception { 
        int returnResult = testFinallyFunc(); 
        System.out.println("get return result " + returnResult); 
    } 
}

finally中return语句的时候的结果如下:
catch 2
finally 3
get return result 3

finally中没有return语句的时候的结果如下:
catch 2
finally 3
get return result 2

  结论:
  try catch finally 都有返回:最终都会得到finally的返回结果。
  try catch 都有返回 finally没有返回:try出现异常,会得到catch的返回结果。finally中的操作,不影响返回结果。
  try catch 都有返回 finally没有返回:try没有异常,会得到try的返回结果。  finally中的操作,不影响返回结果。

有了上面的这个理论,之后,看下面的这个程序的返回结果,应该是多少。

    private static int testFunc2() { 
        int x = 1; 
        try { 
            return x; 
        } catch (Exception e) { 
            System.out.println(e.getMessage()); 
        } finally { 
            ++x; 
        } 
        return x; 
    }



评论关闭
IT序号网

微信公众号号:IT虾米 (左侧二维码扫一扫)欢迎添加!