How not captured eight core basics of exception handling 7. Thread

A. Why do we need UncaughtExceptionHandler

1. The main thread can easily unusual, but it's not the child thread

  • Run the following program found that abnormal child thread will appear in the console displays an error message instead of terminating the main thread of the program, the program is still running hard to find the error message

public class ExceptionInChildThread implements Runnable {
    @Override
    public void run() {
        throw new RuntimeException();
    }

    public static void main(String[] args) {
        new Thread(new ExceptionInChildThread()).start();
        for (int i = 0; i < 1000; i++) {
            System.out.println(i);
        }
    }
}

2. The sub-thread exception can not be captured by traditional methods

  • As can be seen from the following program, when the first thread throws an exception and not the end of the program continues until three thread exception is thrown and the main program is finished. Not continue for the average abnormal when an exception will be the first to capture exception handling.

  • This is due to an abnormality occurs in the run method of each thread, the main thread can not capture sub-thread exception

public class CantCatchDirectly implements Runnable {
    @Override
    public void run() {
        throw new RuntimeException();
    }

    public static void main(String[] args) {
        try {

            new Thread(new CantCatchDirectly(), "thread1").start();
            Thread.sleep(100);
            new Thread(new CantCatchDirectly(), "thread2").start();
            Thread.sleep(100);
            new Thread(new CantCatchDirectly(), "thread3").start();

        } catch (InterruptedException e) {
            System.out.println("捕获到异常");
        }
    }
}

3.UncaughtExceptionHandler treatment will improve the robustness of the program

II. Both solutions abnormal processing threads

1. a program (not recommended): manually try / catch process at each run method

2. Option II (recommended): exception processing using an interface UncaughtExceptionHandler

  • UncaughtExceptionHandler接口

  • void uncaughtException(Thread t, Throwable e);

Call strategy (1) exception handler

  • If there is a parent exception handling thread calls the parent thread

  • If you do not realize it is determined whether the user's own exception handler that he realized the exception handler is invoked own implementation, there is no information on the default printing stack

 

 (2) to achieve their own exception handler

Method to realize:

  1. To set up a unified program

  2. To set up an independent thread

  3. To the thread pool settings

Custom exception trap: implements  Thread.UncaughtExceptionHandler  Interface

import java.util.logging.Level;
import java.util.logging.Logger;

public class MyUncaughtExceptionHandler implements Thread.UncaughtExceptionHandler {

    private String name;

    public MyUncaughtExceptionHandler(String name) {
        this.name = name;
    }

    @Override
    public void uncaughtException(Thread t, Throwable e) {
        Logger logger = Logger.getAnonymousLogger();

        logger.log(Level.WARNING, "线程异常,终止啦" + t.getName(), e);
        System.out.println(name + "Exception capture" + t.getName () + "abnormal" + E); 
    } 
}

Use your own exception catcher

public class UseOwnUncaughtExceptionHandler implements Runnable {
    @Override
    public void run() {
        throw new RuntimeException();
    }

    public static void main(String[] args) throws InterruptedException {
        Thread.setDefaultUncaughtExceptionHandler(new MyUncaughtExceptionHandler("捕获器1"));

        new Thread(new CantCatchDirectly(), "thread1").start();
        Thread.sleep(100);

        new Thread(new CantCatchDirectly(), "thread2").start();
        Thread.sleep(100);

        new Thread(new CantCatchDirectly(), "thread3").start();
    }
}

 

Guess you like

Origin www.cnblogs.com/zhihaospace/p/12519575.html