大家好,又见面了,我是你们的朋友全栈君。
在讲之前我们先看一段程序:
public class Test {
public static void main(String[] args) {
System.out.println("return value of getValue(): " +
getValue());
}
public static int getValue() {
try {
return 0;
} finally {
return 1;
}
}
}
请问答案是:“return value of getValue():0 还是 return value of getValue():1”呢?
在分析此问题之前先看看它们的介绍:
try catch finally 是java中的异常处理的常用标识符,常用的组合为:
1.
try {
//逻辑代码
}catch(exception e){
//异常处理代码
} finally{
//一定要执行的代码
}
2.
try {
//逻辑代码
}catch(exception e){
//异常处理代码
}
3.
try{
//逻辑代码
}finally{
//一定要执行的代码
}
try { //执行的代码,其中可能有异常。一旦发现异常,则立即跳到catch执行。否则不会执行catch里面的内容 }
catch { //除非try里面执行代码发生了异常,否则这里的代码不会执行 }
finally { //不管什么情况都会执行,包括try catch 里面用了return ,可以理解为只要执行了try或者catch,就一定会执行 finally }
其实这些都还好理解,主要就是finally中的代码执行顺序的问题,这里给出我的想法:
例如某些操作,如关闭数据库等。
为了证实我的猜想,我们来看几个例子:
代码1:
public class Test {
public static void main(String[] args) {
System.out.println("return value of getValue(): " +
getValue());
}
public static int getValue() {
try {
System.out.println("try...");
throw new Exception();
} catch(Exception e){
System.out.println("catch...");
return 0;
}finally {
System.out.println("finally...");
return 1;
}
}
}
运行结果:
try...
catch...
finally...
return value of getValue(): 1
代码2:(将return 1 注释)
public class Test {
public static void main(String[] args) {
System.out.println("return value of getValue(): " +
getValue());
}
public static int getValue() {
try {
System.out.println("try...");
throw new Exception();
} catch(Exception e){
System.out.println("catch...");
return 0;
}finally {
System.out.println("finally...");
//return 1;
}
}
}
运行结果:
try...
catch...
finally...
return value of getValue(): 0
讲到这里,前面题目的答案也就知道了,是“return value of getValue():1”。
当在try中要return的时候,判断是否有finally代码,如果有,先执行finally,所以直接return 1.
发布者:全栈程序员栈长,转载请注明出处:https://javaforall.cn/147367.html原文链接:https://javaforall.cn
扫码关注腾讯云开发者
领取腾讯云代金券
Copyright © 2013 - 2025 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号:粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287
Copyright © 2013 - 2025 Tencent Cloud.
All Rights Reserved. 腾讯云 版权所有