码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2020-02-06 12:29:41      阅读:83      评论:0      收藏:0      [点我收藏+]

标签:改变   try catch   run   nbsp   system   idea   color   vat   dea   

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语句时的执行情况剖析

标签:改变   try catch   run   nbsp   system   idea   color   vat   dea   

原文地址:https://www.cnblogs.com/liaowenhui/p/12268142.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!