验证中...
Languages: Java
Categories: Web开发技术
Latest update 2019-10-10 11:42
创建自己的全局未捕获异常处理器
Raw Copy
package com.example.demo;
import lombok.extern.slf4j.Slf4j;
/**
* <h1>我的UncaughtExceptionHandler<h1>
*
* 为什么需要UncaughtExceptionHandler
* 主线程可以轻松发现异常,而子线程不行
* 子线程异常无法用传统方式捕获,try...catch只能捕获对应线程内的异常
* @author: InedibleMushroom
* @create: 2019-10-10 11:25
**/
@Slf4j
public class MyUncaughtExceptionHandler implements Thread.UncaughtExceptionHandler {
@Override
public void uncaughtException(Thread t, Throwable e) {
log.warn("线程异常终止! {}", t.getName(), e);
}
}
设置使用自己的未捕获异常处理器
Raw Copy
package com.example.demo;
import java.util.concurrent.TimeUnit;
/**
* <h1>使用我的UncaughtExceptionHandler<h1>
*
* @author: InedibleMushroom
* @create: 2019-10-10 11:28
**/
public class UseMyUncaughtExceptionHandler implements Runnable{
public static void main(String[] args) throws InterruptedException {
Thread.setDefaultUncaughtExceptionHandler(new MyUncaughtExceptionHandler());
new Thread(new UseMyUncaughtExceptionHandler(), "MyThread-1").start();
TimeUnit.SECONDS.sleep(1);
new Thread(new UseMyUncaughtExceptionHandler(), "MyThread-2").start();
TimeUnit.SECONDS.sleep(1);
new Thread(new UseMyUncaughtExceptionHandler(), "MyThread-3").start();
TimeUnit.SECONDS.sleep(1);
new Thread(new UseMyUncaughtExceptionHandler(), "MyThread-4").start();
}
@Override
public void run() {
throw new RuntimeException();
}
}

Comment list( 0 )

You need to Sign in for post a comment

Help Search