2014-10-16 1 views
2

하나의 스레드에서 호출 된 스레드로 던져진 예외를 어떻게 전달할 수 있습니까?Java 1.3에서 UncaughtExceptionHandler 구현

자바 버전 1.3을 사용해야합니다. Thread.UncaughtExceptionHandler이 Java 1.5에 추가되었습니다.

try 블록에서 코드를 래핑하고 예외를 유발 한 스레드 내부에서 예외를 catch해야한다면 매우 행복합니다. 내 질문은 어떻게 다른 스레드에이 예외를 전달할 수 있습니다.

감사합니다.

답변

0

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"); 
}