public class ClassB {
public static String test(int i) {
int num = 10;
try {
num = num / i;
return "success - " + num;
} catch (Exception e) {
num = num + 50;
return "fail - " + num;
} finally {
num = num + 100;
System.out.println("finally - " + num);
}
}
public static void main(String[] args) {
System.out.println(ClassB.test(5));
System.out.println("--------");
System.out.println(ClassB.test(0));
}
}
这是一道高频面试题,面试者通常喜欢考验的try,catch,finally的执行顺序,以及之变化对下一步的影响
这里肯定的是,try先执行,catch在遇到异常后执行,finally总会执行,在finally执行完
注意的有这么几点
1.try中值变化,会传递到catch,finally,如果没有遇到一场,return里的值变化也会影响到finally
2.catch中值变化,也会影响到fianlly,return里值变化也会影响到finally
3.finally中之值变化,不会影响到try和catch
目前的执行结果是:
finally - 102
success - 2
--------
finally - 160
fail - 60
如果把代码改成如下,再return里加上自增
public class ClassB {
public static String test(int i) {
int num = 10;
try {
num = num / i;
return "success - " + ++num;
} catch (Exception e) {
num = num + 50;
return "fail - " + ++num;
} finally {
num = num + 100;
System.out.println("finally - " + ++num);
}
}
public static void main(String[] args) {
System.out.println(ClassB.test(5));
System.out.println("--------");
System.out.println(ClassB.test(0));
}
}
这个时候,try再没有遇到异常之前,return中的++num会自增1再传导到finally
catch中return的++num也会自增1传导到finally
而finally的值++num是不会传导到try和catch中
执行结果如下:
finally - 104
success - 3
--------
finally - 162
fail - 61