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
Yes, there is a way to throw a checked exception from the run()
method, but it's so terrible I won't share it.
Here's what you can do instead; it uses the same mechanism that a runtime exception would exercise:
@Override
public void run() {
try {
/* Do your thing. */
...
} catch (Exception ex) {
Thread t = Thread.currentThread();
t.getUncaughtExceptionHandler().uncaughtException(t, ex);
}
}
As others have noted, if your run()
method is really the target of a Thread
, there's no point in throwing an exception because it is unobservable; throwing an exception has the same effect as not throwing an exception (none).
If it's not a Thread
target, don't use Runnable
. For example, perhaps Callable is a better fit.