4

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.

bragboy
  • 34,892
  • 30
  • 114
  • 171
user710818
  • 23,228
  • 58
  • 149
  • 207

4 Answers4

5

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.

Gergely Szilagyi
  • 3,813
  • 1
  • 14
  • 12
3

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.

bragboy
  • 34,892
  • 30
  • 114
  • 171
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.

Eager
  • 225
  • 1
  • 8
0

You have to handle exceptions inside run method :

        @Override
        public void run() {
           try {
              innerMethod();
           } catch (Exception e) {
             //handle e
           }
Nandkumar Tekale
  • 16,024
  • 8
  • 58
  • 85