1. try catch 在for循环外面
public class TryCatchDemo1 {
public static void main(String[] args) {
tryOutside();
}
public static void tryOutside() {
try {
for (int count = 1; count <= 5; count++) {
if (count == 3) {
//故意制造一下异常
int num = 1 / 0;
} else {
System.out.println("count:" + count + " 业务正常执行");
}
}
} catch (Exception e) {
System.out.println("try catch 在for 外面的情形, 出现了异常,for循环显然被中断");
}
}
}
执行结果:
count:1 业务正常执行
count:2 业务正常执行
try catch 在for 外面的情形, 出现了异常,for循环显然被中断
结论:
try catch 在 for 循环 外面 的时候, 如果 for循环过程中出现了异常, 那么for循环会终止。
2. try catch 在for循环里面
public class TryCatchDemo2 {
public static void main(String[] args) {
tryInside();
}
public static void tryInside() {
for (int count = 1; count <= 5; count++) {
try {
if (count == 3) {
//故意制造一下异常
int num = 1 / 0;
} else {
System.out.println("count:" + count + " 业务正常执行");
}
} catch (Exception e) {
System.out.println("try catch 在for 里面的情形, 出现了异常,for循环显然继续执行");
}
}
}
}
执行结果:
count:1 业务正常执行
count:2 业务正常执行
try catch 在for 里面的情形, 出现了异常,for循环显然继续执行
count:4 业务正常执行
count:5 业务正常执行
结论:
try catch 在 for 循环 里面 的时候, 如果 for循环过程中出现了异常,异常被catch抓掉,不影响for循环 继续执行。
3. 性能差别
统计一下try catch 在for循环里面的内存消耗情况
public class TryCatchDemo3 {
public static void main(String[] args) {
tryInsideCensus();
}
public static void tryInsideCensus() {
long beginTime = System.currentTimeMillis();
Runtime runtime = Runtime.getRuntime();
// 获取当前剩余内存
long memory = runtime.freeMemory();
System.out.println("memory: " + memory);
for (int count = 1; count <= 300000; count++) {
try {
if (count == 2) {
//故意制造一下异常
int num = 1 / 0;
} else {
System.out.println("count:" + count + " 业务正常执行");
}
} catch (Exception e) {
System.out.println("try catch 在for 里面的情形");
}
}
long endTime = System.currentTimeMillis();
System.out.println("endTime - beginTime = " + (endTime - beginTime));
System.out.println("freeMemory1: " + memory);
System.out.println("freeMemory2: " + runtime.freeMemory());
System.out.println("freeMemory1 - freeMemory2 = " + (memory - runtime.freeMemory())/10000 + "W bytes");
}
}
执行结果:
endTime - beginTime = 2602
freeMemory1: 109171744
freeMemory2: 104393928
freeMemory1 - freeMemory2 = 477W bytes
结论:
也就是说, try catch 放在 for 循环里面 ,因为出现异常不会终止 for循环。所以如果真的存在大批量业务处理全是异常,有那么一定的内存消耗情况。