try catch finally语句块中存在return语句时的执行情况剖析

Posted liaowenhui

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了try catch finally语句块中存在return语句时的执行情况剖析相关的知识,希望对你有一定的参考价值。

2种场景

(1) try中有return,finally中没有return(注意会改变返回值的情形);
(2) try中有return,finally中有return;

场景代码分析(idea亲测)

场景一:

 1 //实例一:try中有return,finally中没有return
 2 public class TryReturnFinally {
 3     public static void main(String[] args) {
 4         System.out.println(test());
 5     }
 6     private static int test(){
 7         int num = 10;
 8         try{
 9             System.out.println("try");
10             return num += 80;
11         }catch(Exception e){
12             System.out.println("error");
13         }finally{
14             if (num > 20){
15                 System.out.println("num>20 : " + num);
16             }
17             System.out.println("finally");
18         }
19         return num;
20     }
21 }

run:

try
num>20 : 90
finally
90

 

 1 //实例二:try中有return,finally中没有return,但是会改变返回值的情况
 2 public class TryReturnFinally {
 3     public static void main(String[] args) {
 4         System.out.println(test());
 5     }
 6     private static int test(){
 7         int num = 10;
 8         try{
 9             System.out.println("try");
10             return num;
11         }catch(Exception e){
12             System.out.println("error");
13         }finally{
14             if (num > 20){
15                 System.out.println("num>20 : " + num);
16             }
17             System.out.println("finally");
18             num = 100;
19         }
20         return num;
21     }
22 }

run:

try
finally
10

 

场景二:

 1 //try中有return,finally中有return
 2 public class TryReturnFinally {
 3     public static void main(String[] args) {
 4         System.out.println(test());
 5     }
 6     private static int test(){
 7         int num = 10;
 8         try{
 9             System.out.println("try");
10             return num += 80;
11         }catch(Exception e){
12             System.out.println("error");
13         }finally{
14             if (num > 20){
15                 System.out.println("num>20 : " + num);
16             }
17             System.out.println("finally");
18             num = 100;
19             return num;
20         }
21     }
22 }

run:

1 try
2 num>20 : 90
3 finally
4 100

 

 

以上是关于try catch finally语句块中存在return语句时的执行情况剖析的主要内容,如果未能解决你的问题,请参考以下文章

Java深入学习23:try catch finally执行和返回逻辑

java异常中try或catch语句中可以有return语句吗?如有return会执行finall

Java中try catch finally语句中含有return语句的执行情况

Java中try catch finally语句中含有return语句的执行情况

JAVA语言如何进行异常处理,关键字throws,throw,try,catch,finally分别代表啥意义在try块中抛出异常吗

Java中try catch finally语句中含有return语句的执行情况(总结版)