多线程异常处理

来源:互联网 发布:购买淘宝小号安全吗 编辑:程序博客网 时间:2024/05/20 09:10

JAVA 主线程中创建子线程,子线程出现异常,如何处理呢?

在线程内种的run()方法中处理对异常进行try catch 捕获
代码如下,异常类

public class TestThread implements Runnable {    private static int resultCode = 0;    @Override    public void run() {        try {            test();        } catch (Exception e) {            resultCode = 1;        }finally {            System.out.println(resultCode);        }    }    public void test()    {        Integer divident =10;        Integer dividor =null;        System.out.println(divident/dividor);    }}

Main 类

public class Main {    public static void main(String[] args) {        TestThread thread = new TestThread();        Thread t = new Thread(thread);        t.start();    }}

结果:

1Process finished with exit code 0

补充:如果只是捕捉异常的话,在子线程中的错误有些事难以扑捉的而且是运行错误,导致子线程暂停,但是,主线程很难监控子线程,所以当你的代码可能会遇到一些运行错误如内存溢出时,推荐捕捉Throwable,这是exception的父类,同时也是error的父类,如果业务逻辑不分error和exception的 话,那么推荐用throwable来抛出。

0 0
原创粉丝点击