突然被问到一个问题在循环中如果出现异常会不会继续执行循环,开始的猜测是会,然后写了代码验证了一下如下
public static void main(String[] args) {
int q = 0;
for(int i = 0;i<5;i++){
System.out.println(q++);
try {
String a = null;
a.equals("");
} catch (Exception e) {
e.printStackTrace();
}
}
}
执行结果如下
0
java.lang.NullPointerException
1
2
3
4
at com.blue.test.Test.main(Test.java:11)
java.lang.NullPointerException
at com.blue.test.Test.main(Test.java:11)
java.lang.NullPointerException
at com.blue.test.Test.main(Test.java:11)
java.lang.NullPointerException
at com.blue.test.Test.main(Test.java:11)
java.lang.NullPointerException
at com.blue.test.Test.main(Test.java:11)
证实了确实程序继续执行,因为异常捕获不会中断程序,而如果把代码改成以下形式那就会中断程序了
public static void main(String[] args) throws Exception {
int q = 0;
for(int i = 0;i<5;i++){
System.out.println(q++);
try {
String a = null;
a.equals("");
} catch (Exception e) {
throw new Exception();
}
}
}
执行结果如下
0
Exception in thread "main" java.lang.Exception
at com.blue.test.Test.main(Test.java:13)
特此记录