如何从线程捕获异常
2022-08-31 06:15:06
我有Java主类,在类中,我启动一个新线程,在主类中,它等待线程死亡。在某个时刻,我从线程中引发运行时异常,但我无法捕获从 main 类中的线程引发的异常。
代码如下:
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)
{
}
}
}
有人知道为什么吗?