Why a new type parameter for exception transparency?

tronicek at fit.cvut.cz tronicek at fit.cvut.cz
Sat Nov 21 02:09:46 PST 2009


Hi,

[Neal, the reference to closures-v07a.html on javac.info does not work.]

Using the declaration from the proposal

public static <T,throws E extends Exception>
T withLock(Lock lock, #T() throws E block) throws E {
    lock.lock();
    try {
        return block.invoke();
    } finally {
        lock.unlock();
    }
}

I understand we can use withLock as follows:

withLock(lock, #() {
    Thread.sleep(1000);  // throws InterruptedException
    new FileInputStream("x").close();  // throws FileNotFoundException and
IOException
});

and the compiler infers that E is InterruptedException or IOException and
will force us to catch both of them. This is why we need the throws
keyword.
In accordance with the proposal I use "or" (InterruptedException or
IOException) but more logical seems to be "and", as this is the compile
time checking. The compiler must infer that the method may throw
InterruptedException AND IOException.
[The NumberFormatException used in the proposal is not a good choice
because it is a runtime exception.]

So far, so good. Now, let's use the throws keyword in a method declaration:

public <throws E extends Exception> void throwit(boolean b, E e1, E e2)
throws E {
   if (b) throw e1;
   else throw e2;
}

and call it:

throwit(b, new InterruptedException(), new IOException());

If E is inferred the same way, does it mean that e1 and e2 are of
different types?
Does it make sense to use E as a type (except that it can be thrown from
the method)?

Zdenek
-- 
Zdenek Tronicek
FIT CTU in Prague


Cituji Paul Benedict <pbenedict at apache.org>:

> Neal,
>
>> Perhaps another approach would be to just take the hint from the
>> fact that the type parameter's bound is a checked exception type.  That is
>> not strictly backward source-compatible, but it might be compatible enough
>> to allow us to simplify the syntax as you suggest.
>
> You read my mind! I was hoping you could infer it.
>
> Anyway, if we take closures out of the discussion, I imagine the new
> type is usable outside of closures, correct? For example:
>
> public <throws E extends Exception> void throwit(E e) throws E {
>    throw e;
> }
>
> But really, the compiler should know what to do just with this:
>
> public <E extends Exception> void throwit(E e) throws E {
>    throw e;
> }
>
> I might be missing something, but is there any important distinction
> between the two?
>
> Paul
>




More information about the closures-dev mailing list