现在的位置: 首页 > 综合 > 正文

含有return 的try catch finally的执行顺序

2013年09月20日 ⁄ 综合 ⁄ 共 1206字 ⁄ 字号 评论关闭

 static int f() {//这里报编译错误:must return a resutl of type int!
  int id = 0;
try {
return id;
} catch (Exception e) {

} finally {

}
}

static int f2() {//但是这里怎么不报 错误呢?
  int id = 0;
try {
return id;
} finally {
}
}
-------- try catch finally顺序:
1.try {}.
2.如果有Error Exception则,执行catch(){}中的代码。
3.无论有没有 Error Exception都要执行finally{}中的代码。
4.执行 try 中的 return
----------------------------------------------我的问题是----------------
1. 函数f中为什么报错误?在try中有return 啊!怎么说 must return a resutl of type int?? 当去掉catch之后,却没有报错误了,为什么呢???

2.谁能详细的说一说 try中有return的时候的 try catch finally return 的执行顺序??

 

 

首先说明一下:
  1,编译错误,是在运行前按java语法,报的。
  2,try-catch-finally,
  如果try语句块遇到异常,try下面的代码就不执行了,转而执行catch语句块。
  try-finally,
  如果try语句块遇到异常,try下面的代码就不执行了.
  但是上面2种情况,finally都会在之后被执行
  3,return
  只要执行了return就会立即结束方法(函数),即使finally没执行也一样。
  所以,当JVM在try-catch中遇到return时,就会先执行finally,执行完finally后
  再回过头来return.
  ---当然如果finally中也有return的话,就会执行这个return,并结束方法,
  其他的return不会被执行。
关于1题:  
  try-catch-finally情况:
  JVM不确定到底会不会执行catch{},所以强迫catch{},return。就会报编译错误
  而try-finally情况:就不会报编译错误

关于2题:
  你可以用Eclipse设置个断点验证一下
附,我的测试代码

Java code
    static Object f(){
        int id = 0; 
        try { 
            System.out.println("before");
            return id; 
        } catch (Exception e) { 
            //throw new Exception();
            return 0;
        } finally { 
            System.out.println(123);
            return 2;
        } 

另外在补充一下:
  return,和throw new Exception();效果差不多
  都是会结束方法,并且都会返回值,(throw是让上一层“捕获到”)

抱歉!评论已关闭.