gpt4 book ai didi

java - 如何从线程捕获异常

转载 作者:行者123 更新时间:2023-12-02 04:25:35 26 4
gpt4 key购买 nike

我有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() {
@Override
public void uncaughtException(Thread th, Throwable ex) {
System.out.println("Uncaught exception: " + ex);
}
};
Thread t = new Thread() {
@Override
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 - 如何从线程捕获异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56609243/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com