inference of throws type parameters in SAMs

Peter Levart peter.levart at
Tue Oct 30 10:25:52 PDT 2012

On 10/30/2012 05:30 PM, Maurizio Cimadamore wrote:
> On 30/10/12 16:18, Peter Levart wrote:
>> Which indicates that the inference algorithm does it's job correctly.
>> But the following program:
>>       public static void main(String... args)
>>       {
>>           MyStream<String> stream = null;
>>           String first = stream.findFirstOrElse(() -> "NO VALUE");
>>       }
>> Triggers the compilation failure:
>> error: unreported exception Throwable; must be caught or declared to be
>> thrown
>>           String first = stream.findFirstOrElse(() -> "NO VALUE");
> There are no constraints on the inference variable E - so, the 
> language infers E to be the declared bound, namely Throwable. What 
> type do you suggest the language/compiler infer in such situation?

I assume that the constraints in the following example:

     public static void main(String... args) throws IOException
         Stream<String> stream = null;
         String first = stream.findFirstOrElse(() -> {throw new 

come from lambda's body throwing IOException, which is the opposite 
direction than other non-throws types, but such is my observation. Am I 

In any case, a Nothing type might be needed for a nice solution.

But until that time, compiler could "hack" around with no visible effect 
on the compilation results in a way similar to this:

If there're no throw statements in lambda body then compiler might 
choose the most general unchecked exception type that satisfies the E's 

For example in the following case:

ThrowingFactory<T, E extends Exception> {
    T make() throws E;
} could choose RuntimeException:

In the following case:

ThrowingFactory<T, E extends Throwable> {
    T make() throws E;

...there are two candidates: RuntimeException and Error (it could choose 
arbitrarily - wouldn't matter).

But in a case where there is no unchecked exception type that fits E's 
bound such as:

ThrowingFactory<T, E extends IOException> {
    T make() throws E;

...the compiler would choose E's bound itself - IOException in this case.

Regards, Peter

> Maurizio

More information about the lambda-dev mailing list