I asked around regarding catching checked exceptions in the context of a thread; the accepted answer was to use Callables and Futures.

But I realized that I can simply wrap the "working" method with Anonymous thread and catch the exception as it would be executed without threads.

(The worker's logic was moved from a new class that implemented Callable to the caller class)

class BlaBla{

public void foo(){

Thread th = new Thread(new Runnable() {
  public void run() {
    try {
    doWork();
    } catch (MyCheckedException e) {
      dosomething();
    }
  }
});
th.start();
}

public void dowork throws MyCheckedException{
}

Is there any problem with this approach?

有帮助吗?

解决方案

Yes, that should work so long as you know what you're doing in those doWork and doSomething methods.

Is it accessing data that other threads also can access? If so then you should think about protecting that using synchronized or some other thread-safe method like message passing between threads using a thread-safe message queue. You'll have to think about what is best to solve your problem.

It would be interesting to know a little bit more about what it's doing because when you wrap it up in a thread you need to think about how to get data to and from that thread in a thread-safe manner. There is probably a simple and safe way to get the job done but it depends on the situation.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top