import org.junit.Test;
/**
* @author John.Jiang
* @date 2018/10/5 19:59
*
* main是一个线程,内部还有个线程对象
* 多线程环境下,无法使用try_catch捕获异常,需要设置UncaughtExceptionHandler
*/
public class TestUncaughtException {
public static void main(String[] args) {
{
try {
Thread thread = new Thread(new Task());
//thread.setUncaughtExceptionHandler(new myHandler());
thread.start();
} catch (Exception e) {
System.out.println("==Exception: " + e.getMessage());
}
}
}
@Test
public void test(){
System.out.println(3/0);
}
}
class Task implements Runnable {
@Override
public void run() {
System.out.println(3 / 2);
System.out.println(3 / 0);
System.out.println(3 / 1);
}
}
class myHandler implements Thread.UncaughtExceptionHandler {
@Override
public void uncaughtException(Thread t, Throwable e) {
System.out.println("==Exception: " + e.getMessage());
System.out.println(t.getId() + "--" + t.getPriority() + "--" + t.getName() + "--" + t.getState());
for (StackTraceElement element : t.getStackTrace()) {
System.out.println(element);
}
}
}
java--Thread.UncaughtExceptionHandler
最新推荐文章于 2024-08-24 21:01:59 发布