try-catch遇到循环时,将try代码块放在循环内还是循环外的选择

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

  

 

posted @ 2018-01-06 08:24  zeng1_cn  阅读(2526)  评论(0编辑  收藏  举报