为了账号安全,请及时绑定邮箱和手机立即绑定

如何从线程捕获异常

如何从线程捕获异常

陪伴而非守候 2019-07-17 09:36:12
如何从线程捕获异常我有Javamain类,在这个类中,我启动了一个新线程,在主线程中,它一直等到线程死掉。在某个时刻,我从线程抛出一个运行时异常,但无法捕获主类中从线程抛出的异常。以下是代码:public class Test extends Thread{   public static void main(String[] args) throws InterruptedException   {     Test t = new Test();     try     {       t.start();       t.join();     }     catch(RuntimeException e)     {       System.out.println("** RuntimeException from main");     }     System.out.println("Main stoped");   }   @Override   public void run()   {     try     {       while(true)       {         System.out.println("** Started");         sleep(2000);         throw new RuntimeException("exception from thread");       }     }     catch (RuntimeException e)     {       System.out.println("** RuntimeException from thread");       throw e;     }      catch (InterruptedException e)     {     }   }}有人知道为什么吗?
查看完整描述

3 回答

?
慕的地8271018

TA贡献1796条经验 获得超4个赞

Thread.UncaughtExceptionHandler.

Thread.UncaughtExceptionHandler h = new Thread.UncaughtExceptionHandler() {
    public void uncaughtException(Thread th, Throwable ex) {
        System.out.println("Uncaught exception: " + ex);
    }};Thread t = new Thread() {
    public void run() {
        System.out.println("Sleeping ...");
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            System.out.println("Interrupted.");
        }
        System.out.println("Throwing exception ...");
        throw new RuntimeException();
    }};t.setUncaughtExceptionHandler(h);t.start();


查看完整回答
反对 回复 2019-07-17
?
动漫人物

TA贡献1815条经验 获得超10个赞

这是因为异常是线程的本地异常,而主线程实际上没有看到run方法。我建议你读更多关于线程工作原理的文章,但是快速总结一下:你的呼吁start启动另一个线程,与主线程完全无关。打电话给join只要等着做就行了。在线程中抛出且从未捕获的异常将终止它,这就是为什么。join返回主线程,但异常本身丢失。

如果您想知道这些不明确的异常,可以尝试如下:

Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
    @Override
    public void uncaughtException(Thread t, Throwable e) {
        System.out.println("Caught " + e);
    }});

有关非正常异常处理的更多信息可以找到。这里.


查看完整回答
反对 回复 2019-07-17
  • 3 回答
  • 0 关注
  • 408 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信