2. 线程的未捕获异常UncaughtException应该如何处理? 2.1 为什么需要UncaughtExceptionHandler?run()方法不可以向上抛出异常,只可以自己捕获,抛出异常后,线程停止运行,进入终止状态。
- 主线程可以轻松发现异常,子线程却不行
public class ExceptionInChildThread implements Runnable{
@Override
public void run() {
throw new RuntimeException("运行出错");
}
public static void main(String[] args) {
new Thread(new ExceptionInChildThread()).start();
for (int i = 0; i < 1000; i++) {
System.out.println(i);
}
}
}
输出结果
程序结果分析
从输出结果来看,子线程抛出异常,主线程并没有停止,而是继续执行,这就造成在实际生产过程中可能遗漏子线程异常信息 。
- 子线程异常无法用传统方法捕获
public class CantCatchDirectly implements Runnable{
@Override
public void run() {
throw new RuntimeException(Thread.currentThread().getName() + "caught exception");
}
public static void main(String[] args) throws InterruptedException {
try{
new Thread(new CantCatchDirectly(),"whale").start();
TimeUnit.MILLISECONDS.sleep(300);
new Thread(new CantCatchDirectly(),"shark").start();
TimeUnit.MILLISECONDS.sleep(300);
new Thread(new CantCatchDirectly(),"salmon").start();
TimeUnit.MILLISECONDS.sleep(300);
new Thread(new CantCatchDirectly(),"regalecus glesne").start();
}catch (RuntimeException e){
System.out.println("catch exception ");
}
}
}
输出结果
Exception in thread "shark" Exception in thread "salmon" Exception in thread "whale" Exception in thread "regalecus glesne" java.lang.RuntimeException: sharkcaught exception at com.whaleson.threadcoreknowledge.uncaughtexception.CantCatchDirectly.run(CantCatchDirectly.java:14) at java.lang.Thread.run(Thread.java:748) java.lang.RuntimeException: regalecus glesnecaught exception at com.whaleson.threadcoreknowledge.uncaughtexception.CantCatchDirectly.run(CantC atchDirectly.java:14) at java.lang.Thread.run(Thread.java:748) java.lang.RuntimeException: whalecaught exception at com.whaleson.threadcoreknowledge.uncaughtexception.CantCatchDirectly.run(CantCatchDirectly.java:14) at java.lang.Thread.run(Thread.java:748) java.lang.RuntimeException: salmoncaught exception at com.whaleson.threadcoreknowledge.uncaughtexception.CantCatchDirectly.run(CantCatchDirectly.java:14) at java.lang.Thread.run(Thread.java:748) Process finished with exit code 0
程序结果分析
从输出结果来看,线程whale抛出,主线程并没有捕获异常,这是因为try catch只能捕获对应线程内的异常。
- 不能直接捕获的后果、提高健壮性
- 方案一(不推荐):手动在每个run方法里进行try catch
public class CantCatchDirectly implements Runnable{
@Override
public void run() {
try{
throw new RuntimeException(Thread.currentThread().getName() + "caught exception");
}catch (RuntimeException e){
System.out.println("Caught exception.");
}
}
public static void main(String[] args) throws InterruptedException {
new Thread(new CantCatchDirectly(),"whale").start();
TimeUnit.MILLISECONDS.sleep(300);
new Thread(new CantCatchDirectly(),"shark").start();
TimeUnit.MILLISECONDS.sleep(300);
new Thread(new CantCatchDirectly(),"salmon").start();
TimeUnit.MILLISECONDS.sleep(300);
new Thread(new CantCatchDirectly(),"regalecus glesne").start();
}
}
- 方案二(推荐):利用UncaughtException
- UncaughtExceptionHandler接口
- void uncaughtException(Thread t, Throwable e);
- 异常处理器的调用策略
public class ThreadGroup implements Thread.UncaughtExceptionHandler {
public void uncaughtException(Thread t, Throwable e) {
if (parent != null) {
parent.uncaughtException(t, e);
} else {
Thread.UncaughtExceptionHandler ueh =
Thread.getDefaultUncaughtExceptionHandler();
if (ueh != null) {
ueh.uncaughtException(t, e);
} else if (!(e instanceof ThreadDeath)) {
System.err.print("Exception in thread ""
+ t.getName() + "" ");
e.printStackTrace(System.err);
}
}
}
}
自定义实现未处理异常
需要实现Thread.UncaughtExceptionHandler
import java.util.logging.Level;
import java.util.logging.Logger;
public class SharkUncaughtExceptionHandler implements Thread.UncaughtExceptionHandler{
@Override
public void uncaughtException(Thread t, Throwable e) {
Logger logger = Logger.getAnonymousLogger();
logger.log(Level.WARNING, " thread has exception " + t.getName());
System.out.println(" current thread name is " + t.getName() + " exception message : " + e.getMessage());
}
}
将自定义的未捕获异常处理器添加到线程中。
public class UseOwnUncaughtExceptionHandler implements Runnable{
@Override
public void run() {
throw new RuntimeException(Thread.currentThread().getName() + "caught exception");
}
public static void main(String[] args) throws InterruptedException {
Thread.setDefaultUncaughtExceptionHandler(new SharkUncaughtExceptionHandler());
new Thread(new UseOwnUncaughtExceptionHandler(), "whale").start();
TimeUnit.MILLISECONDS.sleep(300);
new Thread(new UseOwnUncaughtExceptionHandler(),"shark").start();
TimeUnit.MILLISECONDS.sleep(300);
new Thread(new UseOwnUncaughtExceptionHandler(),"salmon").start();
TimeUnit.MILLISECONDS.sleep(300);
new Thread(new UseOwnUncaughtExceptionHandler(),"regalecus glesne").start();
}
}
输出结果
一月 02, 2022 8:12:42 下午 com.whaleson.threadcoreknowledge.uncaughtexception.SharkUncaughtExceptionHandler uncaughtException 警告: thread has exception whale current thread name is whale exception message : whalecaught exception 一月 02, 2022 8:12:42 下午 com.whaleson.threadcoreknowledge.uncaughtexception.SharkUncaughtExceptionHandler uncaughtException 警告: thread has exception shark current thread name is shark exception message : sharkcaught exception 一月 02, 2022 8:12:43 下午 com.whaleson.threadcoreknowledge.uncaughtexception.SharkUncaughtExceptionHandler uncaughtException 警告: thread has exception salmon current thread name is salmon exception message : salmoncaught exception current thread name is regalecus glesne exception message : regalecus glesnecaught exception 一月 02, 2022 8:12:43 下午 com.whaleson.threadcoreknowledge.uncaughtexception.SharkUncaughtExceptionHandler uncaughtException 警告: thread has exception regalecus glesne
使用lambda表达式自定义未捕获异常处理器
import java.util.concurrent.TimeUnit;
import java.util.logging.Level;
import java.util.logging.Logger;
public class UseOwnUncaughtExceptionHandler implements Runnable{
@Override
public void run() {
throw new RuntimeException(Thread.currentThread().getName() + "caught exception");
}
public static void main(String[] args) throws InterruptedException {
Thread.UncaughtExceptionHandler uncaughtExceptionHandler = (t, e)->{
Logger logger = Logger.getAnonymousLogger();
logger.log(Level.WARNING, " thread has exception " + t.getName());
System.out.println(" current thread name is " + t.getName() + " exception message : " + e.getMessage());
};
Thread.setDefaultUncaughtExceptionHandler(uncaughtExceptionHandler);
new Thread(new UseOwnUncaughtExceptionHandler(), "whale").start();
TimeUnit.MILLISECONDS.sleep(300);
new Thread(new UseOwnUncaughtExceptionHandler(),"shark").start();
TimeUnit.MILLISECONDS.sleep(300);
new Thread(new UseOwnUncaughtExceptionHandler(),"salmon").start();
TimeUnit.MILLISECONDS.sleep(300);
new Thread(new UseOwnUncaughtExceptionHandler(),"regalecus glesne").start();
}
}



