trycatch中return語句如何執行


測試代碼如下:

 1 package reviewTest;
 2 
 3 /**
 4  * @ClassName: ReturnTest
 5  * @Description: 測試return在trycatch中的執行
 6  * @author Kingram
 7  * @date 2018年7月27日
 8  *
 9  */
10 public class ReturnTest {
11 
12     public static void main(String[] args) {
13         System.out.println(new ReturnTest().test());
14     }
15 
16     private int test() {
17         int x = 1;
18         try {
19             int[] arr = new int[2];
20             x = arr[5];
21             return x;
22         } catch (Exception e) {
23             x = 10;
24             return x;
25         } finally {
26             ++x;
27             return x;
28         }
29     }
30 
31 }

程序執行分析:

  當程序執行到第20行時會產生數組下標越界異常,這時直接跳到catch語句塊,此時x==10,並沒有return。

  最終執行finally語句塊此時x==11,並返回x,最終輸出結果為11。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM