目录
情况1:try{}catch{}finally{}return
public int try_catch_finally() {
int i=0;
try{
System.out.println("enter try");
i+=11;
//i/=0;
}catch (Exception e){
System.out.println("enter catch");
i+=12;
}finally {
System.out.println("enter finally");
i+=13;
}
System.out.println("enter return");
return i;
}
无异常:
enter try
enter finally
enter return
24
有异常(取消i除以0的注释):
enter try
enter catch
enter finally
enter return
36
情况2:try{return}catch{}finally{}return
public int try_catch_finally() {
int i=0;
try{
System.out.println("enter try");
i+=11;
//i/=0;
return i;
}catch (Exception e){
System.out.println("enter catch");
i+=12;
//return i;
}finally {
System.out.println("enter finally");
i+=13;
}
System.out.println("enter return");
return i;
}
无异常:虽然执行了finally块,但返回的是try块中return语句之前的代码的执行结果,不受finally块影响
enter try
enter finally
11
有异常(取消i除以0的注释):
enter try
enter catch
enter finally
enter return
36
情况3:try{}catch{return}finally{}return
public int try_catch_finally() {
int i=0;
try{
System.out.println("enter try");
i+=11;
//i/=0;
}catch (Exception e){
System.out.println("enter catch");
i+=12;
return i;
}finally {
System.out.println("enter finally");
i+=13;
}
System.out.println("enter return");
return i;
}
无异常:
enter try
enter finally
enter return
24
有异常(取消i除以0的注释):与情况2类似,虽然执行了finally块中代码但返回的仍是catch块中return语句之前的代码的执行结果
enter try
enter catch
enter finally
23
情况4:try{(return)}catch{(return)}finally{return}
把return写到finally块中,则一定在finally块中返回,不用管try块和catch块中的return,程序按顺序执行。
情况5:try{return}catch{}return
public int try_catch_finally() {
int i=0;
try{
System.out.println("enter try");
i+=11;
//i/=0;
return i;
}catch (Exception e){
System.out.println("enter catch");
i+=12;
}
System.out.println("enter return");
return i;
}
无异常:
enter try
11
有异常(取消i除以0的注释):
enter try
enter catch
enter return
23
情况6:try{}catch{return}return
public int try_catch_finally() {
int i=0;
try{
System.out.println("enter try");
i+=11;
//i/=0;
}catch (Exception e){
System.out.println("enter catch");
i+=12;
return i;
}
System.out.println("enter return");
return i;
}
无异常:
enter try
enter return
11
有异常(取消i除以0的注释):
enter try
enter catch
23
情况7:try{return}catch{}finally{}
public void test() {
try {
if (RandomUtil.randomInt(0, 2) == 1) {
log.info("if");
return;
}
log.info("else");
} finally {
// 必定触发
log.info("finally");
}
}
if
finally
或
else
finally
其他:try{return}catch{return}finally{}return
原因:参考情况2,try和catch都有return的情况下,执行完finally块中内容就会返回。还有类似的不可达情况,就不一一列举了,清楚原理就可以应对。
如果本文对你有所帮助,希望可以点个赞。
如果发现本文有错误,欢迎在评论区指出。
参考:https://www.zhihu.com/question/20805826/answer/83665792