首页 技术 正文
技术 2022年11月20日
0 收藏 809 点赞 3,465 浏览 1523 个字

try catch finally 执行顺序面试题总结

执行顺序

今天牛客网遇到这个题目,做对了,但是下面的评论却很值得看看

public class TestTry {    public int add(int a, int b){
try {
return a + b;
} catch (Exception e) {
System.out.println("catch语句");
} finally {
System.out.println("finally语句");
} return 0;
}
public static void main(String[] args) {
TestTry testTry = new TestTry();
System.out.println(testTry.add(14, 15));
}
}

这个题目答案是

finally语句
29

那么为什么是这样呢?

程序执行到try{}语句中的return方法时,它会干这么一件事,将要返回的结果存储到一个临时栈中,然后程序不会立即返回,而是去执行finally{}中的程序,等finally{}执行完成之后再返回

下面这个

public class Test02 {    public int add(int a){
try {
a ++;
System.out.println("try a = " + a);
return a;
} catch (Exception e) {
a ++;
System.out.println("catch a = " + a);
return a;
} finally {
a = 10;
System.out.println("finally a = " + a);
}
}
public static void main(String[] args) {
Test02 test02 = new Test02();
System.out.println(test02.add(0));
}
}

结果为

try a = 1
finally a = 10
1

下面这个

public class Test03 {    public int add(int a){
try {
a ++;
System.out.println("try a = " + a);
return a;
} catch (Exception e) {
a ++;
System.out.println("catch a = " + a);
return a;
} finally {
a = 10;
System.out.println("finally a = " + a);
return a;
}
}
public static void main(String[] args) {
Test03 test03 = new Test03();
System.out.println(test03.add(0));
}}

可以看到,是从finally语句块中返回的

try a = 1
finally a = 10
10

下面这个有异常的情况下

public class Test04 {
public int add(int a){
try {
a ++;
int m = a / 0;
System.out.println("try a = " + a);
return a;
} catch (Exception e) {
a ++;
System.out.println("catch a = " + a);
return a;
} finally {
a = 10;
System.out.println("finally a = " + a);
return a;
}
} public static void main(String[] args) {
Test04 test04 = new Test04();
System.out.println(test04.add(0));
}
}

catch a = 2
finally a = 10
10

可以看到,因为finally中有return语句,try、catch中的异常被消化掉了,屏蔽了异常的发生,这与初期使用try、catch的初衷是相违背的

相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:8,943
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,469
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,283
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,098
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:7,729
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:4,766