Is there a way to make Runnable's run() throw an exception?

前端 未结 9 1215
忘了有多久
忘了有多久 2020-12-07 14:43

A method I am calling in run() in a class that implements Runnable) is designed to be throwing an exception.

But the Java compiler won\'t let me do that and suggests

9条回答
  •  不思量自难忘°
    2020-12-07 15:39

    You can use a Callable instead, submitting it to an ExecutorService and waiting for result with FutureTask.isDone() returned by the ExecutorService.submit().

    When isDone() returns true you call FutureTask.get(). Now, if your Callable has thrown an Exception then FutureTask.get() wiill throw an Exception too and the original Exception you will be able to access using Exception.getCause().

提交回复
热议问题