Java异常处理体系
(下图截取自慕课网视频)
Error跟Exception都是继承Throwable
Error指的是Java运行过程中系统的内部错误或者资源耗尽,一旦发生,并不能通过代码层面来catch住
Exception分为两种:RuntimeException跟其他异常
RuntimeException是程序的问题,Error跟RuntimeException都是编译器无法预测的,都称非受检查异常
其余称为受检查异常,需要我们在程序中对这些可能出现的异常进行处理
多线程中的异常处理
单线程情况下,如果我们不处理异常,那么程序抛出异常就会终止,多线程情况则不一样
不处理异常会怎么样
测试一
我们有四个子线程,每个都抛出异常
测试代码
@Test
public void test3(){
ThrowExceptionRunnable throwExceptionRunnable = new ThrowExceptionRunnable();
new Thread(throwExceptionRunnable, "thread-1").start();
new Thread(throwExceptionRunnable, "thread-2").start();
new Thread(throwExceptionRunnable, "thread-3").start();
new Thread(throwExceptionRunnable, "thread-4").start();
}
测试结果
结果分析
子线程抛出异常,主线程会继续执行。因为子线程认为,我已经把我发生的异常告诉你了,我的任务已经完成了。那么如果在主程序中trycatch下是否可以呢?
测试二
还是上面的测试用例,我们在主线程中进行trycatch,期望捕获到第一个线程的异常,线程234不应该运行,希望看到打印出catch exception
测试代码
@Test
public void test4(){
try{
ThrowExceptionRunnable throwExceptionRunnable = new ThrowExceptionRunnable();
new Thread(throwExceptionRunna