记阿里Java面试题--try/catch

记阿里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)

  • 懂了吗?
  • 不懂?关注,留言写下问题,小编慢慢解释。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

'嗯哼。

生生不息,“折腾”不止,Thx

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值