for迴圈裡套try-catch-finally,執行流程
阿新 • • 發佈:2019-01-22
package com.demo; public class Test { public static void main(String[] args) throws Exception{ String[] members = new String[4]; for (int count=0;count<6;count++) { try { int x; if (count == 0) x = 1/0; if (count == 1) members[4] = "George Martin"; if (count == 2) continue; if (count == 3) throw new Exception(); if (count == 4) break; if (count == 5) return; } catch (ArrayIndexOutOfBoundsException e) { System.out.println("陣列越界錯誤"); } catch (ArithmeticException e) { System.out.println("除數為零錯誤"); } finally { System.out.println("finally語句塊"); } } } // 11 24 27 // 12 20 27 // 13 27 // 14 27 }
總結一句話:try中有異常,先走異常,再走finally;try沒有異常,不論你continue還是丟擲異常,都會走finally