数梦工厂笔试题回顾一----finally在return之后执行还是之前?
package test; public class TestFinally { public static void main(String[] args) { Demo demo=new Demo(); TestFinally tf=new TestFinally(); String result=tf.fun1(demo); System.out.println(result); System.out.println(demo.str); } private String fun1(Demo demo) { try { demo.str+="1"; return fun2(demo); }finally{ demo.str+="2"; } } private String fun2(Demo demo) { try { demo.str+="3"; return demo.str; }finally{ demo.str+="4"; } } } class Demo{ String str=""; }View Code
执行结果:
13
1342
我写的答案是result=1234 demo.str=1234。在我的记忆中finally是异常捕获关键词,finally代码块一定会执行。但我对其的执行过程并不十分清楚,以前一直认为一旦遇到return返回,即代表函数结束,则finally在return之前执行。所以写出了如上错误结果。而通过正确结果,可以看出,函数在return执行完毕后如果有finally代码块存在,就会在return执行完毕的基础上继续执行finally中的代码块。所以结果为result=12 demo.str=1324。
进一步的,那如果finally中也有return将怎么执行呢?
(1)
package test; public class TestFinally { public static void main(String[] args) { Demo demo=new Demo(); TestFinally tf=new TestFinally(); String result=tf.fun1(demo); System.out.println(result); System.out.println(demo.str); } private String fun1(Demo demo) { try { demo.str+="1"; return fun2(demo); }finally{ demo.str+="2"; } } private String fun2(Demo demo) { try { demo.str+="3"; return demo.str; }finally{ demo.str+="4"; return demo.str;//添加的return语句 } } } class Demo{ String str=""; }View Code
执行结果:
1341342
(2)
package test; public class TestFinally { public static void main(String[] args) { Demo demo=new Demo(); TestFinally tf=new TestFinally(); String result=tf.fun1(demo); System.out.println(result); System.out.println(demo.str); } private String fun1(Demo demo) { try { demo.str+="1"; return fun2(demo); }finally{ demo.str+="2"; return demo.str;//添加的return语句 } } private String fun2(Demo demo) { try { demo.str+="3"; return demo.str; }finally{ demo.str+="4"; } } } class Demo{ String str=""; }View Code
执行结果:
13421342
说明如果finally中也有return。则由于函数在return执行完毕后如果有finally代码块存在,就会在return执行完毕的基础上继续执行finally中的代码块,则finally中的return会覆盖try代码块中的return的结果。
相关推荐
HMHYY 2020-07-28
ELEMENTS爱乐小超 2020-07-04
amazingbo 2020-06-28
alicelmx 2020-06-16
minkee 2020-06-09
逍遥友 2020-06-02
嗡汤圆 2020-05-10
whbing 2020-05-05
zhuxianfeng 2020-05-02
assastor 2020-05-01
JessePinkmen 2020-05-01
hongxiangping 2020-04-30
theta = np.zeros #theta = array,构造全为零的行向量。grad[0,j] = np.sum/len #∑term / m. return value > threshol
Kwong 2020-04-26
88483063 2020-04-23
xirongxudlut 2020-04-19