Because of the thread's nature, when we start a thread there is no way to catch an exception with a try catch, as in the following example:
1 Packagecom.xt.thinks21_2;2 3 ImportJava.util.concurrent.ExecutorService;4 Importjava.util.concurrent.Executors;5 6 /**7 * Thread exception capture Test8 * 9 * @authorXueTen * One */ A Public classThreaduncaughtexceptiontestImplementsRunnable { - - @Override the Public voidrun () { - //TODO auto-generated Method Stub - Throw Newnullpointerexception (); - } + - Public Static voidMain (string[] args) { + Try { AExecutorservice es =Executors.newcachedthreadpool (); atEs.execute (Newthreaduncaughtexceptiontest ()); - Es.shutdown (); - //or this - //thread t = new Thread (new Threaduncaughtexceptiontest ()); - //T.start (); -}Catch(Exception e) { in //Todo:handle Exception - } to + } -}
The print exception information is:
Exception in Thread "Pool-1-thread-1" java.lang.NullPointerException
At Com.xt.thinks21_2.ThreadUncaughtExceptionTest.run (threaduncaughtexceptiontest.java:17)
At Java.util.concurrent.ThreadPoolExecutor.runWorker (Unknown Source)
At Java.util.concurrent.threadpoolexecutor$worker.run (Unknown Source)
At Java.lang.Thread.run (Unknown Source)
At this point, we need to customize the factory class for threads to the production line, specifying Uncaughtexceptionhandler for the thread
1 Packagecom.xt.thinks21_2;2 3 ImportJava.lang.Thread.UncaughtExceptionHandler;4 ImportJava.util.concurrent.ExecutorService;5 Importjava.util.concurrent.Executors;6 Importjava.util.concurrent.ThreadFactory;7 8 /**9 * Exception Execution program not caughtTen * One * @authorAdministrator A * - */ - classThreaduncaughtexceptionhandlerImplementsUncaughtexceptionhandler { the - @Override - Public voiduncaughtexception (Thread T, Throwable e) { - //TODO auto-generated Method Stub +System.out.println ("Caught:" +e); - } + A } at - /** - * Thread Factory - * - * @authorAdministrator - * in */ - classHandlerthreadexceptionfactoryImplementsThreadfactory { to + @Override - PublicThread Newthread (Runnable r) { the //TODO auto-generated Method Stub *Thread T =NewThread (r); $T.setuncaughtexceptionhandler (NewThreaduncaughtexceptionhandler ());Panax Notoginseng returnT; - } the + } A the /** + * Thread exception capture Test - * $ * @authorXue $ * - */ - Public classThreaduncaughtexceptiontestImplementsRunnable { the - @OverrideWuyi Public voidrun () { the //TODO auto-generated Method Stub - Throw Newnullpointerexception (); Wu } - About Public Static voidMain (string[] args) { $Executorservice es =Executors -. Newcachedthreadpool (Newhandlerthreadexceptionfactory ()); -Es.execute (Newthreaduncaughtexceptiontest ()); - Es.shutdown (); A } +}
At this point, we can see that the exception information is captured:
Caught:java.lang.NullPointerException
Java concurrency, thread exception capture