当循环内的代码出现异常,需要结束循环时,将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()); } } }