问题
Code:
outerMethod {
@Override
public void run() {
innerMethod throws IOException
}
}
Method that exceuted in thread throws checked exception - IOException. I need to handle this exception in main thread. Like:
outerMethod() throws IOException
{
@Override
public void run() {
innerMethod() throws IOException
}
}
Is this possible? If no, what would be a better way to do this?
Thanks.
回答1:
Use FutureTask http://docs.oracle.com/javase/6/docs/api/java/util/concurrent/FutureTask.html#get%28%29 . It's get methods will encapsulate any exceptions from the task that might have run on another thread.
ExecutionException: Exception thrown when attempting to retrieve the result of a task that aborted by throwing an exception. This exception can be inspected using the Throwable.getCause() method.
回答2:
Thread is an individual process and you cannot propagate your exception to other thread as they cannot talk through the exception route. However you can use inter thread communication and you will have to logically handle the case when an exception occurs.
回答3:
From this API doc
If thread has defined UncaughtExceptionHandler, it will be invoked, Else thread group's UncaughtExceptionHandler will be invoked if defined, Else it can forward to default uncaught exception handler.
回答4:
You have to handle exceptions inside run method :
@Override
public void run() {
try {
innerMethod();
} catch (Exception e) {
//handle e
}
来源:https://stackoverflow.com/questions/11220971/how-to-propagate-exception-from-thread-in-java