測試代碼如下:
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。