簡體   English   中英

在Java 1.3中實現UncaughtExceptionHandler

[英]Implement UncaughtExceptionHandler in Java 1.3

如何將在一個線程中拋出的異常傳遞給它的調用線程?

我必須使用Java版本1.3。 在Java 1.5中添加了Thread.UncaughtExceptionHandler

如果必須將代碼包裝在try塊中,並因此在導致異常的線程中捕獲異常,我感到非常高興。 我的問題是如何將這個異常傳遞給另一個線程。

謝謝!

可以通過synced,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");
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM