java多线程编程之捕获子线程异常示例
程序员文章站
2024-02-24 16:22:16
通过try catch是无法捕获子线程异常的,thread对象提供了setuncaughtexceptionhandler(thread.uncaughtexception...
通过try catch是无法捕获子线程异常的,thread对象提供了setuncaughtexceptionhandler(thread.uncaughtexceptionhandler eh)方法用来获取线程中产生的异常。
复制代码 代码如下:
package threads;
import java.lang.thread.uncaughtexceptionhandler;
public class textexception
{
public static void main(string[] args)
{
test test = new test();
test.setuncaughtexceptionhandler(new uncaughtexceptionhandler()
{
public void uncaughtexception(thread t, throwable e)
{
system.out.println(t.getname() + " : " + e.getmessage());
// todo
}
});
}
public static class test extends thread
{
public test()
{
}
public void run()
{
throw new runtimeexception("just a test");
}
}
}