Java 8 Lambda function that throws exception?

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

    By default, Java 8 Function does not allow to throw exception and as suggested in multiple answers there are many ways to achieve it, one way is:

    @FunctionalInterface
    public interface FunctionWithException {
        R apply(T t) throws E;
    }
    

    Define as:

    private FunctionWithException myMethod = (str) -> {
        if ("abc".equals(str)) {
            throw new IOException();
        }
      return 1;
    };
    

    And add throws or try/catch the same exception in caller method.

提交回复
热议问题