简体   繁体   中英

Catch Exception from running Thread

I want to catch an exception from a running thread and handle it in the calling thread. How would I to that the best way?

try {
  Runnable connect = new Runnable() {
    public synchronized void  run() {
      try {
        ... some code requiring long time
      } catch(Exception e) {
        ..I want to catch here and send to calling thread
      }
    }
  }

  synchronized(connect) {
    new Thread(connect).start();
    connect.wait();
    ...if exception then handle it
    ...keep on with code if no exception occurred
  }

} catch(Exception e) {
}

The best was is to not use Thread directly, but instead use a Future . you can run a FutureTask via a Thread if you desire, or get a Future by submitting a Callable to an Executor (the preferred method). the Future gives you a convenient way to wait for the task to complete and to deal with the results (regular or exceptional).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM