Thread catch Exception:
Case, we are in the main () method is not catching the exception of the thread, than for example with the following code:
public class Exceptionthread implements runnable{ @Override public void Run () { throw new NullPointerException (); } public static void Main (string[] args) { Executorservice executorservice = Executors.newcachedthreadpool (); try { System.out.println ("Running thread"); Executorservice.execute (New Exceptionthread ()); } catch (Exception e) { e.printstacktrace (); System.out.println ("catch Exception");}}}
The above code does not catch thread exceptions in the main method, so how can we capture the thread's exception information?
Let's look at the code below
/** * Define exception thread content */class Myexceptionthread implements Thread.uncaughtexceptionhandler {@Override public void uncaught Exception (Thread T, Throwable e) {///catch exception after the business processing is placed here System.out.println ("Catch exception information such as the following"); System.out.println (e); }}/** * Define exception Thread factory */class Exceptionthreadfactory implements threadfactory {@Override public thread newthread (runnabl E r) {thread thread = new Thread (r); Here is the setting to catch the exception. Thread.setuncaughtexceptionhandler (New Myexceptionthread ()); return thread; }}/** * Execution Thread */class ExceptionThread2 implements runnable{@Override public void Run () {try {Thr Ead.sleep (1000l); } catch (Interruptedexception e) {e.printstacktrace (); }//Throw exception throw new NullPointerException (); } public static void Main (string[] args) {//through our own exceptionthreadfactory thread factory, construct thread pool Executorservice ex Ecutorservice = Executors.newcachedthreadpool (New ExceptiOnthreadfactory ()); try {System.out.println ("execution thread"); Start three threads Executorservice.execute (new ExceptionThread2 ()); Executorservice.execute (New ExceptionThread2 ()); Executorservice.execute (New ExceptionThread2 ()); } catch (Exception e) {e.printstacktrace (); System.out.println ("catch exception"); } }}The result of the above output is
The exception information that is captured by running threads such as the following java.lang.NullPointerException catch exception information such as the following java.lang.NullPointerException catch exception information such as the following JAVA.LANG.NULLPOINTEREXC Eption
The conclusion is: Main () The method still does not catch the exception of the thread, of course, this setting is reasonable. Now each thread has its own exception handling mechanism, how to do it, sentence, when creating a thread, the statement is good ~
Call it
Java Thread Learning Note (two) thread exception handling