在Java 1.3中实现UncaughtExceptionHandler
如何将在一个线程中抛出的异常传递给其调用线程 我必须使用Java版本1.3。是在Java1.5中添加的 如果我必须将代码包装在一个try块中,从而捕获导致异常的线程中的异常,我会非常高兴。我的问题是如何将此异常传递给另一个线程在Java 1.3中实现UncaughtExceptionHandler,java,multithreading,Java,Multithreading,如何将在一个线程中抛出的异常传递给其调用线程 我必须使用Java版本1.3。是在Java1.5中添加的 如果我必须将代码包装在一个try块中,从而捕获导致异常的线程中的异常,我会非常高兴。我的问题是如何将此异常传递给另一个线程 谢谢 可以使用synchronized、wait()和notify()将异常传递给调用线程 class MyThread extends Thread implements Runnable { public Throwable exception; // a cop
谢谢 可以使用synchronized、wait()和notify()将异常传递给调用线程
class MyThread extends Thread implements Runnable {
public Throwable exception; // a copy of any exceptions are stored here
public void run() {
try {
throw new Exception("This is a test");
}
catch (Throwable e) {
// An exception has been thrown. Ensure we have exclusive access to
// the exception variable
synchronized(this) {
exception = e; // Store the exception
notify(); // Tell the calling thread that exception has been updated
}
return;
}
// No exception has been thrown
synchronized(this) {
// Tell the calling thread that it can stop waiting
notify();
}
}
}
MyThread t = new MyThread();
t.start();
synchronized(t) {
try {
System.out.println("Waiting for thread...");
t.wait();
System.out.println("Finished waiting for thread.");
}
catch (Exception e) {
fail("wait() resulted in an exception");
}
if (t.exception != null) {
throw t.exception;
}
else {
System.out.println("Thread completed without errors");
}
}
try {
System.out.println("Waiting to join thread...");
t.join();
System.out.println("Joined the thread");
}
catch (Exception e) {
System.out.println("Failed to join thread");
}