(1)如果catch块中有返回语句,则先执行finally语句块中的代码。
public class Main {
public static void main(String[] args) {
System.out.println(test());
}
public static String test(){
try{
int i=10/0;
}catch(Exception e){
return "catch";
}finally{
System.out.println("finally");
}
return null;
}
}
输出结果:
finally
catch
(2)如果catch块和finally块中均有返回语句,则finally块中的返回语句会覆盖catch块中的返回语句,即catch块执行到return语句之前会执行finally块中的代码。
public static String test(){
try{
int i=10/0;
}catch(Exception e){
return "catch";
}finally{
return "finally";
}
}
输出结果:
finally
(3)如果catch块中有System.exit(0)语句,则直接退出程序。
public static String test(){
try{
int i=10/0;
}catch(Exception e){
System.out.println("exit之前");
System.exit(0);
System.out.println("exit之后");
return "catch";
}finally{
return "finally";
}
输出结果:
exit之前