當循環內的代碼出現異常,須要結束循環時,將try代碼塊放在循環外;java
當循環內的代碼出現異常,須要繼續執行循環時,將try代碼塊放在循環內。spa
public static void main(String[] args) { int runs = 3; //循環運行次數 //try代碼塊在循環外 try { for (int i = 0; i < runs; i++) { if (i == 0) { throw new RuntimeException("try在循環外時,出現運行異常"); } System.out.println("do something..."); } } catch (Exception e) { System.out.println(e.getMessage()); } System.out.println("--------------------------"); //try代碼塊在循環內 for (int i = 0; i < runs; i++) { try { if (i == 0) { throw new RuntimeException("try在循環內時,出現運行異常"); } System.out.println("do something..."); } catch (Exception e) { System.out.println(e.getMessage()); } } }