当循环内的代码出现异常,需要结束循环时,将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()); } } }
原文地址:https://www.cnblogs.com/zengdb/p/8213272.html
时间: 2024-10-08 02:39:48