java 主线程捕获子线程异常_Java中主线程如何捕获子线程抛出的异常

记不得在哪里看到的代码,可以处理到线程中抛出的RuntimeException:

public   class   ApplicationLoader   extends   ThreadGroup

{

private   ApplicationLoader()

{

super("ApplicationLoader");

}

public   static   void   main(String[]   args)

{

Runnable   appStarter   =   new   Runnable()

{

public   void   run()

{

//invoke   your   application   (i.e.MySystem.main(args)

throw   new   NullPointerException();   //example,   throw   a   runtime   exception

}

};

new   Thread(new   ApplicationLoader(),   appStarter).start();

}

//We   overload   this   method   from   our   parent

//ThreadGroup   ,   which   will   make   sure   that   it

//gets   called   when   it   needs   to   be.     This   is

//where   the   magic   occurs.

public   void   uncaughtException(Thread   thread,   Throwable   exception)

{

//Handle   the   error/exception.

//Typical   operations   might   be   displaying   a

//useful   dialog,   writing   to   an   event   log,   etc.

exception.printStackTrace();//example,   print   stack   trace

}

}

呵呵,uncaughtException好像是唯一能够处理线程抛出的uncaught异常的入口。看来还是有细心人啊。确实如此,通过ThreadGroup的uncaughtException方法还是有处理的机会。当线程抛出uncaughtException的时候,JVM会调用ThreadGroup的此方法。默认的处理如下:

<<

public   void   uncaughtException(Thread   t,   Throwable   e)   {

if   (parent   !=   null)   {

parent.uncaughtException(t,   e);

}   else   if   (!(e   instanceof   ThreadDeath))   {

e.printStackTrace(System.err);

}

}

>>

每个Thread都会有一个ThreadGroup对象,可以通过Thread.getThreadGroup()方法得到,提供了上述默认的uncaught异常处理方法。

上面没有提这点,因为俺认为在正常的情况下,这个方法的处理情况就已经足够了。还是那个线程设计的理念:“线程的问题应该线程自己本身来解决,而不要委托到外部。”通常情况下,外部不需要处理线程的异常。当然也有例外。:)

posted on 2009-08-07 12:38 Frank_Fang 阅读(5851) 评论(1)  编辑  收藏 所属分类: Java编程

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值