Java8 Lambdas and Exceptions

后端 未结 5 2051
面向向阳花
面向向阳花 2020-11-29 02:16

I wonder if someone could explain the following weirdness to me. I\'m using Java 8 update 11.

Given this method

private  T runFun(Function         


        
5条回答
  •  被撕碎了的回忆
    2020-11-29 02:38

    This looks like a case of bug JDK-8054569, which doesn't affect Eclipse.

    I was able to narrow it down by replacing Function with Supplier and extracting the orElseThrow method:

    abstract  void f(Supplier s);
    
    abstract  T g(Supplier x) throws X;
    
    void bug() {
        f(() -> g(() -> new RuntimeException("foo")));
    }
    

    and then further by removing the suppliers and lambdas altogether:

    abstract  void f(T t);
    
    abstract  T g(X x) throws X;
    
    void bug() {
        f(g(new RuntimeException("foo")));
    }
    

    which is actually a cleaner example than the one in the bug report. This shows the same error if compiled as Java 8, but works fine with -source 1.7.

    I guess something about passing a generic method return type to a generic method parameter causes the type inference for the exception to fail, so it assumes the type is Throwable and complains that this checked exception type isn't handled. The error disappears if you declare bug() throws Throwable or change the bound to X extends RuntimeException (so it's unchecked).

提交回复
热议问题