项目场景:
提示:这里简述相关背景:
如果在 try 中 return , 那么 finaly 会执行吗?
如果执行,是谁先?
如果在两处都 return 了 ,那最终的数据以哪个为准确?
在try中返回
public static void main(String[] args) {
System.out.println(doSomething() + "<-----方法返回值");
}
static String doSomething(){
try {
System.out.println("try执行了");
return "a";
}catch (Exception e){
}finally {
System.out.println("finally执行了");
return "b";
}
}
输出:
try执行了
finally执行了
b<-----方法返回值
在catch中返回
public static void main(String[] args) {
System.out.println(doSomething() + "<-----方法返回值");
}
static String doSomething(){
try {
System.out.println("try执行了");
throw new RuntimeException("给它报个错!");
}catch (Exception e){
System.out.println("catch执行了");
return "a";
}finally {
System.out.println("finally执行了");
return "b";
}
}
输出
try执行了
catch执行了
finally执行了
b<-----方法返回值
总结:
通过例子我们可以发现:
如果在 try 中 return , 那么 finally 会执行
执行顺序是先 try 最后才是 finally
如果在两处都 return 了 ,那最终的数据是以 finally 为准确