2016-07-05 14:46:09 -06:00
|
|
|
// threads/CaptureUncaughtException.java
|
2015-12-15 11:47:04 -08:00
|
|
|
// (c)2016 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.
|
|
|
|
// Visit http://mindviewinc.com/Books/OnJava/ for more book information.
|
2015-06-15 17:47:35 -07:00
|
|
|
// {TimeOutDuringTesting}
|
|
|
|
import java.util.concurrent.*;
|
|
|
|
|
|
|
|
class ExceptionThread2 implements Runnable {
|
|
|
|
@Override
|
|
|
|
public void run() {
|
|
|
|
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) {
|
|
|
|
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) {
|
|
|
|
ExecutorService exec = Executors.newCachedThreadPool(
|
|
|
|
new HandlerThreadFactory());
|
|
|
|
exec.execute(new ExceptionThread2());
|
|
|
|
}
|
2015-09-07 11:44:36 -06:00
|
|
|
}
|
|
|
|
/* Output:
|
2015-12-15 11:47:04 -08:00
|
|
|
HandlerThreadFactory@10dea4e creating new Thread
|
2015-06-15 17:47:35 -07:00
|
|
|
created Thread[Thread-0,5,main]
|
2015-12-15 11:47:04 -08:00
|
|
|
eh = MyUncaughtExceptionHandler@647e05
|
2015-06-15 17:47:35 -07:00
|
|
|
run() by Thread[Thread-0,5,main]
|
2015-12-15 11:47:04 -08:00
|
|
|
eh = MyUncaughtExceptionHandler@647e05
|
|
|
|
HandlerThreadFactory@10dea4e creating new Thread
|
|
|
|
created Thread[Thread-1,5,main]
|
|
|
|
eh = MyUncaughtExceptionHandler@c34ec2
|
2015-06-15 17:47:35 -07:00
|
|
|
caught java.lang.RuntimeException
|
2015-09-07 11:44:36 -06:00
|
|
|
*/
|