线程遇到异常该怎么处理

134 阅读1分钟

众所周知,实现 Runnable接口还是 Thread类也好,只要重写了 run()方法,是没有办法把异常往外抛的,那怎么办?

直接在 run()方法中,把要处理的异常catch掉

public class ExceptionHandling {

    public static void main(String[] args) {
        Thread thread = new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    int count = 0;
                    while (true) {
                        ++count;
                        System.out.println("我循环了" + count + "次了");
                        if (count == 5) {
                            throw new RuntimeException();
                        }
                    }
                } catch (RuntimeException e) {
                    System.out.println("异常交给我处理了");
                }
            }
        });
        thread.start();
    }
}

在这里插入图片描述

利用一个计时器count,在循环到5次的时候抛出 RuntimeException,然后让catch处理异常,但这里有个异常,如果我们这个方法是给别人用的呢?那就会出问题了,我们把异常处理了,那边也知道出现了异常,但是没法处理,这样就不好了,那么有更好的方法?

书写普通方法,然后抛出异常,让调用方自己创建线程

public class ExceptionHandling implements Runnable{

    public static void main(String[] args) {
        ExceptionHandling exceptionHandling = new ExceptionHandling();
        Thread thread = new Thread(exceptionHandling);
        thread.start();
    }

    public void generalMethod() throws RuntimeException{
        int count = 0;
        while (true) {
            ++count;
            System.out.println("我循环了" + count + "次了");
            if (count == 5) {
                throw new RuntimeException();
            }
        }
    }

    @Override
    public void run() {
        try {
            generalMethod();
        }catch (RuntimeException e){
            System.out.println("处理了调用方法抛出的异常");
        }
    }
}

在这里插入图片描述
上面我们自己新建了一个方法,在方法中,我们把所要处理的内容处理完,把可能出现的异常往外抛,凡是调用了我们方法的人,都要选择是否要把异常处理下,怎么处理,随调用者的心思


欢迎大家关注下个人的「公众号」:独醉贪欢