Question::
How to catch an Exception from a thread
I have Java main class, in the class, I start a new thread, in the main, it waits until the thread dies. At some moment, I throw a runtime exception from the thread, but I can't catch the exception thrown from the thread in the main class.
Here is the code:
public class Test extends Thread
{
public static void main(String[] args) throws InterruptedException
{
Test t = new Test();
try
{
t.start();
t.join();
}
catch(RuntimeException e)
{
System.out.println("** RuntimeException from main");
}
System.out.println("Main stoped");
}
@Override
public void run()
{
try
{
while(true)
{
System.out.println("** Started");
sleep(2000);
throw new RuntimeException("exception from thread");
}
}
catch (RuntimeException e)
{
System.out.println("** RuntimeException from thread");
throw e;
}
catch (InterruptedException e)
{
}
}
}
Anybody knows why?
Answer::
첫번째답:
Use a Thread.UncaughtExceptionHandler
.
Thread.UncaughtExceptionHandler h = new Thread.UncaughtExceptionHandler() {
public void uncaughtException(Thread th, Throwable ex) {
System.out.println("Uncaught exception: " + ex);
}
};
Thread t = new Thread() {
public void run() {
System.out.println("Sleeping ...");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
System.out.println("Interrupted.");
}
System.out.println("Throwing exception ...");
throw new RuntimeException();
}
};
t.setUncaughtExceptionHandler(h);
t.start();
두번째답:
That's because exceptions are local to a thread, and your main thread doesn't actually see the run
method. I suggest you read more about how threading works, but to quickly summarize: your call to start
starts up a different thread, totally unrelated to your main thread. The call to join
simply waits for it to be done. An exception that is thrown in a thread and never caught terminates it, which is why join
returns on your main thread, but the exception itself is lost.
If you want to be aware of these uncaught exceptions you can try this:
Thread.setDefaultExceptionHandler(new UncaughtExceptionHandler() {
public void unchaughtException(Thread t, Throwable e) {
System.out.println("Caught " + e);
}
});
More information about uncaught exception handling can be found here.
'java' 카테고리의 다른 글
timer schedule vs scheduleAtFixedRate (0) | 2016.06.15 |
---|---|
java.exe와 javaw.exe (0) | 2016.06.10 |
was listener (0) | 2016.04.18 |
Runtime addShutdownHook -퍼옴 (0) | 2016.04.05 |
static에 대한 고찰. 퍼옴. (0) | 2016.04.04 |