According to section 6.3.2 of JCIP :
Runnable is a fairly limiting abstraction; run can not return a value or throw checked exception .
run()
can not return a value since its return type is void but why can not it throw a checked exception ?
It cannot throw a checked exception because it wasn't declared as throwing a checked exception from the first version and it is too dangerous to change it.
Originally Runnable
was only used in a wrapped Thread
, and it was assumed the developer would want to catch all checked exceptions and handle them rather than logging them to System.err
.
Callable
was added when you can add individual tasks to an Executor
where you can capture the result in a Future
and any exception thrown.
Callable
now allows you to return a value and optional declare a checked exception.
BTW: One way you can say you don't want a return or throw a checked exception from a callable is to use something like
Callable<Void> callable = new Callable<Void>() {
public Void call() {
// do something
return null;
}
};
run()
can't throw a checked exception because it is not declared to do so. You can't throw checked exceptions without declaring them.
You also can't declare checked exceptions on a method which overrides or implements another method which doesn't throw that exception. So, implementations of Runnable
can't simply add throws
clauses to their implementations of run()
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With