简体   繁体   中英

Implement UncaughtExceptionHandler in Java 1.3

How can I pass an exception that has been thrown in one thread to its calling thread?

I am obliged to use Java version 1.3. Thread.UncaughtExceptionHandler was added in Java 1.5.

I'm quite happy if I have to wrap my code up in a try block and therefore catch the exception inside the thread that caused the exception. My question is how I can pass this exception to the other thread.

Thanks!

Passing an exception to the calling thread can be done with synchronized, wait(), and 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");
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM