本教程操作环境:windows7系统、java10版,DELL G3电脑。
1.在 try 语句块之前返回(return)或者抛出异常,finally不会被执行
packagecom.zwwhnly.springbootaction;
publicclassFinallyTest{
publicstaticvoidmain(String[]args){
System.out.println("returnvalueoftest():"+test());
}
publicstaticinttest(){
inti=1;
/*if(i==1){
return0;
}*/
System.out.println("thepreviousstatementoftryblock");
i=i/0;
try{
System.out.println("tryblock");
returni;
}finally{
System.out.println("finallyblock");
}
}
}
只有与 finally 相对应的 try 语句块得到执行的情况下,finally 语句块才会执行。
2.有异常,finally 中的 return会导致提前返回
publicstaticStringtest(){
try{
System.out.println("try");
thrownewException();
}catch(Exceptione){
System.out.println("catch");
return"returnincatch";
}finally{
System.out.println("finally");
return"returninfinally";
}
}
调用 test() 的结果:
try catch finally returninfinally
finally 语句块在 try 语句块中的 return 语句之前执行。
原文来自:https://www.py.cn
© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END


















































暂无评论内容