008 Research on Thread Exception

I. Overview

  We know that after a thread runs, it will open another thread stack to complete the operation of its own tasks. At this time, the capture of exceptions is a problem.


 

2. Exceptional demonstration 

public static void main(String[] args) {
        try {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    throw new RuntimeException();
                }
            }).start();
        } catch (Exception e) {
            e.printStackTrace ();
        }
    }

We run the above program and the result is as follows:  

Exception in thread "Thread-0" java.lang.RuntimeException
    at com.trek.concurrency.exception.ExceptionTest$1.run(ExceptionTest.java:10)
    at java.lang.Thread.run(Thread.java:745)

We found that we couldn't catch the exception thrown by the thread at all, just printed the stack information of a thread.


 

3. Use thread exception handlers to complete tasks 

public class ExceptionHandler {
    
    static class Handler implements UncaughtExceptionHandler{
        @Override
        public  void uncaughtException(Thread t, Throwable e) {
             // We just need to print the information here System.out 
            .println ( " Thread name: " + t.getName ());
            System.out.println(e);
        }
    }
    
    public static void main(String[] args) {
        Thread thread = new Thread(new Runnable() {
            @Override
            public  void run() {
                 throw  new RuntimeException( " I threw an exception message " );
            }
            
        });
        thread.setUncaughtExceptionHandler(new Handler());
        thread.start();
    }
}

First, we define an inner class as an exception handler.

  Then we 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- 0 
java.lang.RuntimeException: I threw an exception message

We found that the exception information thrown by the thread can be captured.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325338167&siteId=291194637