try-catch遇到循環時,將try代碼塊放在循環內還是循環外的選擇
阿新 • • 發佈:2018-01-06
cep sage for runt exception string image row ring
當循環內的代碼出現異常,需要結束循環時,將try代碼塊放在循環外;
當循環內的代碼出現異常,需要繼續執行循環時,將try代碼塊放在循環內。
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()); } } }
try-catch遇到循環時,將try代碼塊放在循環內還是循環外的選擇