【正确答案】可以通过设置线程的UncaughtExceptionHandler(异常捕获处理方法)来捕获线程抛出的异常,如下例所示:
class MyThread extends Thread
{
public void run()
{
System.out.println("thread will throw exception");
throw new RuntimeException("My own exception from thread");
}
}
public class Test
{
public static void main(String[]args)
{
Thread.UncaughtExceptionHandler handler=
new Thread.UncaughtExceptionHandler(){
public void uncaughtException(Thread th,Throwable ex){
System.out.println("Uncaught exception:"+ex);
}
};
Thread myThread=new MyThread();
//设置捕获异常的handler
myThread.setUncaughtExceptionHandler(handler);
myThread.start();
}
}程序的运行结果为:thread will throw exception
Uncaught exception:java.1ang.RuntimeException:My own exception from thread
【答案解析】