首页 > 试题广场 >

下述程序执行后输出结果为(   

[不定项选择题]
下述程序执行后输出结果为(    )。
public class TestMain {
public int test(){
int a = 0;
try{
a++;
throw new Exception("故意的");
}catch(Exception exa){
a++;
return a;
}finally{
a++;
System.out.println("a1 = "+a);
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
int a = new TestMain().test();
System.out.println("a2 = "+a);
}
}
  • a1 = 3<div>a2 = 2</div>
  • a2 = 2<div>a1 = 3</div>
  • a2 = 3
  • a2 = 2
再简单排一下版
public class TestMain {
    public int test() {
        int a = 0;
        try {
            a++;
            throw new Exception("故意的");
        }
        catch (Exception exa) {
            a++;
            return a;
        }
        finally{
            a++;
            System.out.println("a1 = " + a);
        }
    }
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        int a = new TestMain().test();
        System.out.println("a2 = " + a);
    }
}


编辑于 2019-09-11 19:47:39 回复(0)
主要考察try catch finally的执行情况。main方法中,进入test方法,try先得a=1,然后抛出异常,进入catch中,a=2,此时要return,但是发现finally中有代码要执行,所以catch中的return先保留计算好的a=2的值,等待finally执行后再返回a=2,finally中a=3,而且立马打印出来了:a1=3,main方法中的a接收的是catch中return的返回值a=2,然后也打印出来:a2=2;
 关键点是,此例子,catch中的return的值不会受到finally执行代码的影响,建议不清楚的同学可以多做几道try catch finally方面题目,这里面还有其他要注意点,比如说return 后面跟的是表达式,是先计算完表达式,还是立马执行finally语句?
发表于 2019-08-24 23:13:26 回复(2)
catch中的return的值不会受到finally执行代码的影响。【这句话是关键】
发表于 2019-09-05 17:22:42 回复(0)
a1 = 3
a2 = 2

Process finished with exit code 0

发表于 2020-03-20 17:30:33 回复(0)