Java 8 Lambda function that throws exception?

后端 未结 26 1754
臣服心动
臣服心动 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:27

    Disclaimer: I haven't used Java 8 yet, only read about it.

    Function doesn't throw IOException, so you can't put any code in it that throws IOException. If you're calling a method that expects a Function, then the lambda that you pass to that method can't throw IOException, period. You can either write a lambda like this (I think this is the lambda syntax, not sure):

    (String s) -> {
        try {
            return myMethod(s);
        } catch (IOException ex) {
            throw new RuntimeException(ex);
            // (Or do something else with it...)
        }
    }
    

    Or, if the method you're passing the lambda to is one you wrote yourself, you can define a new functional interface and use that as the parameter type instead of Function:

    public interface FunctionThatThrowsIOException {
        O apply(I input) throws IOException;
    }
    

提交回复
热议问题