Java 8 Lambda function that throws exception?

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

    You'll need to do one of the following.

    • If it's your code, then define your own functional interface that declares the checked exception:

      @FunctionalInterface
      public interface CheckedFunction {
         R apply(T t) throws IOException;
      }
      

      and use it:

      void foo (CheckedFunction f) { ... }
      
    • Otherwise, wrap Integer myMethod(String s) in a method that doesn't declare a checked exception:

      public Integer myWrappedMethod(String s) {
          try {
              return myMethod(s);
          }
          catch(IOException e) {
              throw new UncheckedIOException(e);
          }
      }
      

      and then:

      Function f = (String t) -> myWrappedMethod(t);
      

      or:

      Function f =
          (String t) -> {
              try {
                 return myMethod(t);
              }
              catch(IOException e) {
                  throw new UncheckedIOException(e);
              }
          };
      

提交回复
热议问题