How to throw an exception from a thread in java?

the code:

outerMethod { @Override public void run() { innerMethod throws IOException } } 

A method that is excluded in checking thread exceptions is an IOException. I need to handle this exception in the main thread. For instance:

 outerMethod() throws IOException { @Override public void run() { innerMethod() throws IOException } } 

Is it possible? If not, what would be the best way to do this?

Thanks.

+4
source share
4 answers

Use FutureTask http://docs.oracle.com/javase/6/docs/api/java/util/concurrent/FutureTask.html#get%28%29 . It receives methods that encapsulate any exceptions to a task that might be running in another thread.

ExecutionException: An exception is thrown while trying to get the result of a task that was interrupted by throwing an exception. This exception can be checked using the Throwable.getCause () method.

+5
source

From this API document

If a thread defines an UncaughtExceptionHandler, it will be called. Another group of UncaughtExceptionHandler threads will be called if it is defined. In addition, it can forward a default exception handler.

+3
source

Thread is a separate process, and you cannot propagate your exception to another thread, because they cannot talk through the exception route. However, you can use the connection between threads, and you will have to logically handle the case when an exception occurs.

+2
source

You must handle exceptions inside the run method:

  @Override public void run() { try { innerMethod(); } catch (Exception e) { //handle e } 
0
source

All Articles