记阿里Java面试题–try/catch
- 关键字:try/catch/finally,return
- 大家都知道try/catch中,finally{…}中代码是一定会执行的,但是当try{…}有return语句呢?
1、原题代码
- 代码如下,问:输出结果是什么?
注:++x 相当于 x=x+1
public class TryCatchDemo {
public int calculate() {
int x = 1;
try {
System.out.println("A");
return ++x;
} catch (Exception e) {
//System.out.println("D");
} finally {
System.out.println("B");
++x;
}
System.out.println("C");
return x;
}
public static void main(String[] args) {
TryCatchDemo tryCatchDemo=new TryCatchDemo();
int y=tryCatchDemo.calculate();
System.out.println(y);
}
}
- 答案:AB2
- 疑惑:为什么不是”3”而是”2”呢?为什么不是”ABC3”?
2、Debug详解
2.1 初始
- 程序启动初始化时,控制台没有任何输出,执行”int x=1”,所以x=1
2.2 输出A过程,执行try{…}中代码
- 执行try{…}中代码,分为两步:
- 第一步:执行”System.out.println(“A”);”,控制台输出A
- 这个时候,还未执行”return ++x”,所以此时x的值仍然没有变,x=1
- 第二步:执行”++x”,此时x=2
- 执行完成后,进入finally{…}代码块
2.3 catch{…}中代码不执行
- 不要疑惑”为什么catch{…}中代码不执行?”,因为对于此题目中代码而言,没有出现异常,所以不会执行catch{…}中代码
2.4 输出B过程,执行finally{…}中代码
- 执行finally{…}中代码同样有两步
- 第一步:控制台输出B
- 执行”System.out.println(“B”);”,但没有执行”++x”,所以此时x=2
- 第二步:执行 ++x,此时x=3
2.5 重点
- 当执行完finally{…}中代码时,会再次回到try{…}中代码,停留在”return ++x”
- 此时此刻x的值为3,停留在”return ++x”,在执行try{…}中代码时已经执行了”return ++x”,那么,这个时候还会再执行”return ++x”中的”++x”吗?不会
- 这个时候是直接返回,直接返回3吗?不,直接返回2
- WF!!!直接返回2?,所以”System.out.println(“C”);return x;”压根就没有执行?是的^ ^
2.6 解释
- 官方解释
If the try clause executes a return, the compiled code does the following:
Saves the return value (if any) in a local variable.
Executes a jsr to the code for the finally clause.
Upon return from the finally clause, returns the value saved in the local variable.
- 翻译官方解释
如果 try 语句里有 return,那么代码的行为如下:
A,有返回值:就把返回值保存到局部变量中
(执行”return ++x”,x=2,保存在局部变量)
B,执行 jsr 指令跳到 finally 语句里执行
(准备执行finally{…}代码块)
C,执行完 finally 语句后,返回之前保存在局部变量表里的值
(虽然执行”++x”后x=3,但是返回保存在局部变量中的x=2)
- 懂了吗?
- 不懂?关注,留言写下问题,小编慢慢解释。