132-如何捕获线程运行期间的异常

捕获线程异常

public static void main(String[] args) {
    Thread t = new Thread(() -> {
        try {
            Thread.sleep(1_000L);
            int result = 10 / 0;
            System.out.println("result = " + result);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    });
    t.start();

    t.setUncaughtExceptionHandler((thread, e) -> {
        System.out.println(e);
        System.out.println(thread.getName());
    });
}

StackTrace。方法调用。

public class ThreadException {
    public static void main(String[] args) {
        new Test1().test();
    }
}
public class Test1 {
    private Test2 test2 = new Test2();

    public void test() {
        test2.test();
    }
}
public class Test2 {
    public void test() {
        StackTraceElement[] stackTrace = Thread.currentThread().getStackTrace();
        Stream.of(stackTrace)
                .filter(e -> !e.isNativeMethod())
                .forEach(e ->
                        Optional.of(e.getClassName() + "." + e.getMethodName() + ":" + e.getLineNumber()).ifPresent(System.out::println)
                );
    }
}

转载请注明来源,欢迎对文章中的引用来源进行考证,欢迎指出任何有错误或不够清晰的表达。可以在下面评论区评论,也可以邮件至 tuyrk@qq.com

文章标题:132-如何捕获线程运行期间的异常

文章字数:121

本文作者:神秘的小岛岛

发布时间:2019-12-07, 20:04:16

最后更新:2019-12-08, 17:42:09

原始链接:https://www.tuyrk.cn/wang-thread/132-catch-thread-exception/

版权声明: "署名-非商用-相同方式共享 4.0" 转载请保留原文链接及作者。

目录
×

喜欢就点赞,疼爱就打赏