1.当 tyr catch 在 for 循环外面时,示例代码如下:
@Test
public void test2() {
try {
for (int num = 1; num <= 5; num++) {
if (num == 3) {
//故意制造一下异常
int number = 1 / 0;
} else {
System.out.println("num:" + num + " 业务正常执行");
}
}
} catch (Exception e) {
System.out.println("try catch 在for 外面的情形, 出现了异常,for循环显然被中断");
}
}
当出现异常时,控制台如下:
结论:try catch 在 for 循环 外面 的时候, 如果 for循环过程中出现了异常, 那么for循环会终止。
2.try catch 在 for 循环里面时,示例代码如下:
@Test
public void test3() {
for (int num = 1; num <= 5; num++) {
try {
if (num == 3) {
//故意制造一下异常
int number = 1 / 0;
} else {
System.out.println("num:" + num + " 业务正常执行");
}
} catch (Exception e) {
System.out.println("try catch在for 里面的情形,出现了异常,for循环显然继续执");
}
}
}
运行代码,控制台如下:
结论:try catch 在 for 循环 里面 的时候, 如果 for循环过程中出现了异常,异常被catch抓掉,不影响for循环 继续执行。
从性能上分析,当代码无异常时,时间相差并不大,内存消耗差距也不大,但是,当代码发生异常时,差距就会很明显。
我们用 Runtime 来统计一下内存消耗的情况
Runtime runtime = Runtime.getRuntime();
long memory = runtime.freeMemory();
总结
try catch 是放在 for 循环里面还是外面,就看业务的需求,如果需要出现异常就终止循环的,就放在外面,不需要终止循环的,就放在里面。