Java 8 Lambda function that throws exception?

后端 未结 26 2188
臣服心动
臣服心动 2020-11-22 03:14

I know how to create a reference to a method that has a String parameter and returns an int, it\'s:

Function         


        
26条回答
  •  情书的邮戳
    2020-11-22 03:22

    This problem has been bothering me as well; this is why I have created this project.

    With it you can do:

    final ThrowingFunction f = yourMethodReferenceHere;
    

    There are a totla of 39 interfaces defined by the JDK which have such a Throwing equivalent; those are all @FunctionalInterfaces used in streams (the base Stream but also IntStream, LongStream and DoubleStream).

    And as each of them extend their non throwing counterpart, you can directly use them in lambdas as well:

    myStringStream.map(f) // <-- works
    

    The default behavior is that when your throwing lambda throws a checked exception, a ThrownByLambdaException is thrown with the checked exception as the cause. You can therefore capture that and get the cause.

    Other features are available as well.

提交回复
热议问题