Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why cannot run() of Runnable throw checked Exceptions?

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 ?

like image 822
Inquisitive Avatar asked Jul 10 '12 09:07

Inquisitive


2 Answers

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;
    }
};
like image 86
Peter Lawrey Avatar answered Sep 22 '22 04:09

Peter Lawrey


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().

like image 45
Tom Anderson Avatar answered Sep 23 '22 04:09

Tom Anderson