码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2018-01-06 11:54:41      阅读:177      评论:0      收藏:0      [点我收藏+]

标签:异常   rgs   system   sage   post   style   mes   cat   --   

当循环内的代码出现异常,需要结束循环时,将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代码块放在循环内还是循环外的选择

标签:异常   rgs   system   sage   post   style   mes   cat   --   

原文地址:https://www.cnblogs.com/zengdb/p/8213272.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!