Java如何从线程中捕获异常

我有Java主类,在该类中,我启动了一个新线程,在主类中,它等待线程死亡。在某个时刻,我从线程中抛出了运行时异常,但是我无法在主类中捕获从线程中抛出的异常。

这是代码:

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)

{

}

}

}

有人知道为什么吗?

回答:

使用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();

以上是 Java如何从线程中捕获异常 的全部内容, 来源链接: utcz.com/qa/418937.html

回到顶部