程序1:try catch捕获异常,不抛出
import java.util.Map;
import java.util.TreeMap;
public class testThrow {
public static void main(String[] args) {
TreeMap<String, String> map = new TreeMap();
map.put("k1", "v1");
map.put("k2", "v2");
map.put("k3", "v3");
map.put("k4", "");
for (Map.Entry<String, String> entry : map.entrySet()) {
System.out.println("Key = " + entry.getKey() + ", Value = "
+ entry.getValue());
}
MyThread r = new MyThread();
r.start();
try {
String a = null;
map.put(a, "value");
System.out.println(a);
System.out.println(map.get(a));
} catch (NullPointerException e) {
System.out.println("a is null");
}
for (int i = 0; i < 200; i++) {
System.out.println("main here " + i);
}
System.out.println("test2test");
}
static class MyThread extends Thread {
public void run() {
for (int i = 0; i < 200; i++) {
System.out.println("MyThread : " + i);
}
}
}
}
运行结果:
1)遍历了map
2)执行捕获异常后的输出,打印了a is null
3)主线程和线程r交互执行,交互打印出结果
4)执行最后的输出:test2test
程序2:直接new 异常
import java.util.Map;
import java.util.TreeMap;
public class testThrow {
public static void main(String[] args) {
TreeMap<String, String> map = new TreeMap();
map.put("k1", "v1");
map.put("k2", "v2");
map.put("k3", "v3");
map.put("k4", "");
for (Map.Entry<String, String> entry : map.entrySet()) {
System.out.println("Key = " + entry.getKey() + ", Value = "
+ entry.getValue());
}
MyThread r = new MyThread();
r.start();
if ("".equals(map.get("k4"))) {
throw new NullPointerException("k4 is null");
//System.out.println("k4 is null");
}
for (int i = 0; i < 200; i++) {
System.out.println("main here " + i);
}
System.out.println("test2test");
}
static class MyThread extends Thread {
public void run() {
for (int i = 0; i < 200; i++) {
System.out.println("MyThread : " + i);
}
}
}
}
运行结果:
1)遍历map
2)抛出异常
Exception in thread "main" java.lang.NullPointerException: k4 is null
at com.test.testThrow.main(testThrow.java:23)
3)执行线程r,打印出MyThread : 0~199
得出结论:
抛出异常之后,程序后续的语句将不会继续执行,不过其他线程不受影响。
------欢迎指出不足之处,谢谢