如何从线程捕获异常我有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 回答
蝴蝶刀刀
TA贡献1801条经验 获得超8个赞
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();
RISEBY
TA贡献1856条经验 获得超5个赞
run
start
join
join
Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() { @Override public void uncaughtException(Thread t, Throwable e) { System.out.println("Caught " + e); }});
添加回答
举报
0/150
提交
取消