未捕获异常
UncaughtExceptionHandler
主线程可以轻松发现异常,子线程却不行
子线程异常无法用传统方法捕获
public class CantCatchDirectly implements Runnable {
public static void main(String[] args) {
try {
new Thread(new CantCatchDirectly(), "Thread-1").start();
Thread.sleep(300);
new Thread(new CantCatchDirectly(), "Thread-2").start();
Thread.sleep(300);
new Thread(new CantCatchDirectly(), "Thread-3").start();
Thread.sleep(300);
new Thread(new CantCatchDirectly(), "Thread-4").start();
Thread.sleep(300);
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
public void run() {
throw new RuntimeException();
}
}
// Exception in thread "Thread-1" java.lang.RuntimeException
// at com.hasson.uncaughtexception.CantCatchDirectly.run(CantCatchDirectly.java:26)
// at java.lang.Thread.run(Thread.java:748)
// Exception in thread "Thread-2" java.lang.RuntimeException
// at com.hasson.uncaughtexception.CantCatchDirectly.run(CantCatchDirectly.java:26)
// at java.lang.Thread.run(Thread.java:748)
// Exception in thread "Thread-3" java.lang.RuntimeException
// at com.hasson.uncaughtexception.CantCatchDirectly.run(CantCatchDirectly.java:26)
// at java.lang.Thread.run(Thread.java:748)
// Exception in thread "Thread-4" java.lang.RuntimeException
// at com.hasson.uncaughtexception.CantCatchDirectly.run(CantCatchDirectly.java:26)
// at java.lang.Thread.run(Thread.java:748)
解决办法
- 手动在每个run方法种使用一个try catch
- 利用UncaughtExceptionHandler
- 每个程序一个
- 每个线程一个
- 给线程池配置