OnJava8-Examples/lowlevel/CaptureUncaughtException.java

55 lines
1.6 KiB
Java
Raw Normal View History

2016-12-07 10:34:41 -08:00
// lowlevel/CaptureUncaughtException.java
// (c)2021 MindView LLC: see Copyright.txt
2015-11-15 15:51:35 -08:00
// We make no guarantees that this code is fit for any purpose.
2016-09-23 13:23:35 -06:00
// Visit http://OnJava8.com for more book information.
2015-06-15 17:47:35 -07:00
import java.util.concurrent.*;
class ExceptionThread2 implements Runnable {
@Override public void run() {
2015-06-15 17:47:35 -07:00
Thread t = Thread.currentThread();
2016-07-05 14:46:09 -06:00
System.out.println("run() by " + t.getName());
2015-06-15 17:47:35 -07:00
System.out.println(
"eh = " + t.getUncaughtExceptionHandler());
throw new RuntimeException();
}
}
class MyUncaughtExceptionHandler implements
Thread.UncaughtExceptionHandler {
@Override
public void uncaughtException(Thread t, Throwable e) {
System.out.println("caught " + e);
}
}
class HandlerThreadFactory implements ThreadFactory {
@Override public Thread newThread(Runnable r) {
2015-06-15 17:47:35 -07:00
System.out.println(this + " creating new Thread");
Thread t = new Thread(r);
System.out.println("created " + t);
t.setUncaughtExceptionHandler(
new MyUncaughtExceptionHandler());
System.out.println(
"eh = " + t.getUncaughtExceptionHandler());
return t;
}
}
public class CaptureUncaughtException {
public static void main(String[] args) {
2017-01-22 16:48:11 -08:00
ExecutorService exec =
Executors.newCachedThreadPool(
new HandlerThreadFactory());
2015-06-15 17:47:35 -07:00
exec.execute(new ExceptionThread2());
2016-12-04 12:15:21 -08:00
exec.shutdown();
2015-06-15 17:47:35 -07:00
}
2015-09-07 11:44:36 -06:00
}
/* Output:
HandlerThreadFactory@106d69c creating new Thread
2016-12-04 12:15:21 -08:00
created Thread[Thread-0,5,main]
eh = MyUncaughtExceptionHandler@52e922
2016-12-04 12:15:21 -08:00
run() by Thread-0
eh = MyUncaughtExceptionHandler@52e922
2015-06-15 17:47:35 -07:00
caught java.lang.RuntimeException
2015-09-07 11:44:36 -06:00
*/