关于程序中抛出异常

程序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

 

得出结论:

抛出异常之后,程序后续的语句将不会继续执行,不过其他线程不受影响。

 

 

                                                                                               ------欢迎指出不足之处,谢谢

 

转载于:https://my.oschina.net/xiaozhiwen/blog/917660

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值