概述:
1、finally中的语句块总会执行,最后执行
2、如果try语句块中出现能被catch捕捉的异常、那么异常语句之后的代码将不会执行。
3、如果try或catch或finally中有return语句执行了,那么finally语句块后的语句将不会执行(此条具体结论看最后总结,此处不太严谨)
测试代码如下:
package com.test;
public class TryCatchFinally {
public static void main(String[] args) {
TryCatchFinally tr=new TryCatchFinally();
int result=tr.test();
System.out.println("the final result is "+result);
}
public int test(){
int a=10;
int b=0;
try{
System.out.println("this is try start");
int c=a/b;
c=c++;
System.out.println("this is try end");
return 1;
}catch(Exception e){
System.out.println("this is catch");
//return 2;
}finally {
System.out.println("this is finally");
// return 3;
}
System.out.println("88");
// return 0;
}
}
情况1:try{}catch{}finally{}retrun
<div style="text-align: left;"><span style="font-family: Arial, Helvetica, sans-serif;"><span style="white-space:pre"> </span>this is try start</span></div><span style="white-space:pre"> </span>this is catch
<div style="text-align: left;"><span style="font-family: Arial, Helvetica, sans-serif;"><span style="white-space:pre"> </span>88</span></div><span style="white-space:pre"> </span>this is finally
<div style="text-align: left;"><span style="font-family: Arial, Helvetica, sans-serif;"><span style="white-space:pre"> </span>the final result is 0</span></div>
按顺序执行
情况2:try{return}catch{}finally{}
报错
情况3:try{return}catch{return}finally{}
<span style="white-space:pre"> </span>this is try start
<span style="white-space:pre"> </span>this is catch
<span style="white-space:pre"> </span>this is finally
<span style="white-space:pre"> </span>the final result is 2
返回值为catch中的return,并且try中异常语句后的代码不执行
情况4:try{return}catch{return}finally{return}
<span style="white-space:pre"> </span>this is try start
<span style="white-space:pre"> </span>this is catch
<span style="white-space:pre"> </span>this is finally
<span style="white-space:pre"> </span>the final result is 3
返回值为finally中的return
情况5:try{}catch{return}finally{return}
结果同上
情况6:try{}catch{return}finally{}
报错
情况7:try{}catch{return}finally{}return
<span style="white-space:pre"> </span>this is try start
<span style="white-space:pre"> </span>this is catch
<span style="white-space:pre"> </span>this is finally
<span style="white-space:pre"> </span>the final result is 2
返回值为catch中的return,finally后的语句不执行
情况8:try{}catch{}finally{return}
<span style="white-space:pre"> </span>this is try start
<span style="white-space:pre"> </span>this is catch
<span style="white-space:pre"> </span>this is finally
<span style="white-space:pre"> </span>the final result is 3
返回值为fianlly中的return
总结:
1、finally中的return较catch中return“等级”高,即若catch与finally中均出现return时,最终返回的是finally中的return
2、若只有catch中有return语句,finally语句后可添加代码,而且必须有return语句,因为编译器并不知道程序会不会出现异常。若程序无异常,fianlly后程序正常执行。若出现异常,返回的值为catch中return的值,而且finally后的代码不会执行。
3、try或finally中有return语句,finally后面任何代码都不能添加。编译器会提示代码不可达,会报错。
(个人总结,仅供参考。如若有错,欢迎指正。)