I. Overview
We know that once a thread is running, it will open another line Cheng to complete its own task, when the exception capture is a problem.
Two. Presentation of the exception
Public Static void Main (string[] args) { try { new Thread (new Runnable () { @Override Public void run () { thrownew runtimeexception (); } }). Start (); Catch (Exception e) { e.printstacktrace (); } }
We run the above procedure with the following results:
inch " Thread-0 " java.lang.RuntimeException at com.trek.concurrency.exception.exceptiontest$1. Run ( Exceptiontest.java:at java.lang.Thread.run (thread.java:745)
We found that we simply could not catch the exception thrown by a thread, simply printing the stack information of a thread.
Three. To complete a task using the thread exception handler
Public classExceptionhandler {Static classHandler implements uncaughtexceptionhandler{@Override Public voiduncaughtexception (Thread T, Throwable e) {//all we need to do is print the information here.System. out. println ("the name of the thread:"+t.getname ()); System. out. println (e); } } Public Static voidMain (string[] args) {thread thread=NewThread (NewRunnable () {@Override Public voidrun () {Throw NewRuntimeException ("I threw out an exception message"); } }); Thread.setuncaughtexceptionhandler (NewHandler ()); Thread.Start (); }}
First, we define an inner class as the exception handler.
We then bind an instance of the exception handler object when creating the thread.
When our thread throws an exception, the exception handler catches the exception.
We look at the results:
Thread Name: thread-0java.lang.RuntimeException: I threw out an exception message
We find that the exception information thrown by the thread we can capture.
008 The research of thread abnormality