时间上, 其实算是无差别。内存上, 如果没出异常,其实也是无差别。
但是如果出现了异常, 那就要注意了。
一、try catch 在 for 循环外面
java
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循环显然被中断");
}
}
try catch 在for循环外面的时候, 如果for循环过程中出现了异常, 那么for循环会终止。
二、try catch 在 for 循环里面
java
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循环显然继续执行");
}
}
}
try catch 在 for 循环里面时, 如果for循环过程中出现了异常,异常被catch抓掉,不影响for循环继续执行。
其实就是看业务。需要出现异常就终止循环的,就放外头;
不需要终止循环,就搞里头。但要注意一点,别在for循环里面去查库调用第三方啥的,这些操作,如果必要,需要慎重考虑了。
可以在**tryInside()
**方法内部的循环中添加统计内存消耗的代码。这样,每次循环执行时都可以记录一下内存的使用情况,这样,在每次循环执行前后,都会输出可用内存的情况,可以通过比较前后两次输出的内存情况来评估内存的消耗情况。
java
public class CompositeTest {
public static void main(String[] args){
tryInside();
}
public static void tryInside() {
Runtime runtime = Runtime.getRuntime();
long begintime = System.currentTimeMillis();
for (int count = 1; count <= 5; count++) {
long beginMemory = runtime.freeMemory(); // 获取当前可用内存
System.out.println("Free Memory before iteration " + count + ": " + beginMemory);
try {
if (count == 3) {
// 故意制造一下异常
int num = 1 / 0;
} else {
System.out.println("count:" + count + " 业务正常执行");
}
} catch (Exception e) {
System.out.println("try catch 在for 里面的情形, 出现了异常,for循环显然继续执行");
}
long endtime = System.currentTimeMillis();
System.out.println(endtime - begintime);
long lastMemory = runtime.freeMemory(); // 获取循环后的可用内存
System.out.println("Free Memory after iteration " + count + ": " + (beginMemory - lastMemory)/10000);
}
}
}
try catch 放在 for 循环里面 ,因为出现异常不会终止 for循环。所以如果真的存在大批量业务处理全是异常,有那么一定的内存消耗情况。
如果说代码没出错的话, try catch 在 for 里面 和 外面 ,都是几乎没区别的。因为 异常try catch 其实一早编译完就标记了 如果从哪儿(from)出现异常,会直接去到(to)的那行代码去。
-
Exception table
: 当前函数程序代码编译涉及到的异常; -
type
:异常类型; -
target
:表示异常的处理起始位; -
from
:表示 try-catch 的开始地址; -
to
:表示 try-catch 的结束地址;