Java 8 Lambda function that throws exception?

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

    I use an overloaded utility function called unchecked() which handles multiple use-cases.


    SOME EAMPLE USAGES

    unchecked(() -> new File("hello.txt").createNewFile());
    
    boolean fileWasCreated = unchecked(() -> new File("hello.txt").createNewFile());
    
    myFiles.forEach(unchecked(file -> new File(file.path).createNewFile()));
    

    SUPPORTING UTILITIES

    public class UncheckedUtils {
    
        @FunctionalInterface
        public interface ThrowingConsumer<T> {
            void accept(T t) throws Exception;
        }
    
        @FunctionalInterface
        public interface ThrowingSupplier<T> {
            T get() throws Exception;
        }
    
        @FunctionalInterface
        public interface ThrowingRunnable {
            void run() throws Exception;
        }
    
        public static <T> Consumer<T> unchecked(
                ThrowingConsumer<T> throwingConsumer
        ) {
            return i -> {
                try {
                    throwingConsumer.accept(i);
                } catch (Exception ex) {
                    throw new RuntimeException(ex);
                }
            };
        }
    
        public static <T> T unchecked(
                ThrowingSupplier<T> throwingSupplier
        ) {
            try {
                return throwingSupplier.get();
            } catch (Exception ex) {
                throw new RuntimeException(ex);
            }
        }
    
        public static void unchecked(
                ThrowingRunnable throwing
        ) {
            try {
                throwing.run();
            } catch (Exception ex) {
                throw new RuntimeException(ex);
            }
        }
    }
    
    0 讨论(0)
  • 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<T, R, E extends Exception> {
        R apply(T t) throws E;
    }
    

    Define as:

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

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

    0 讨论(0)
  • 2020-11-22 03:30

    You can use unthrow wrapper

    Function<String, Integer> func1 = s -> Unthrow.wrap(() -> myMethod(s));
    

    or

    Function<String, Integer> func2 = s1 -> Unthrow.wrap((s2) -> myMethod(s2), s1);
    
    0 讨论(0)
  • 2020-11-22 03:30

    You can.

    Extending @marcg 's UtilException and adding generic <E extends Exception> where necessary: this way, the compiler will force you again to add throw clauses and everything's as if you could throw checked exceptions natively on java 8's streams.

    public final class LambdaExceptionUtil {
    
        @FunctionalInterface
        public interface Function_WithExceptions<T, R, E extends Exception> {
            R apply(T t) throws E;
        }
    
        /**
         * .map(rethrowFunction(name -> Class.forName(name))) or .map(rethrowFunction(Class::forName))
         */
        public static <T, R, E extends Exception> Function<T, R> rethrowFunction(Function_WithExceptions<T, R, E> function) throws E  {
            return t -> {
                try {
                    return function.apply(t);
                } catch (Exception exception) {
                    throwActualException(exception);
                    return null;
                }
            };
        }
    
        @SuppressWarnings("unchecked")
        private static <E extends Exception> void throwActualException(Exception exception) throws E {
            throw (E) exception;
        }
    
    }
    
    public class LambdaExceptionUtilTest {
    
        @Test
        public void testFunction() throws MyTestException {
            List<Integer> sizes = Stream.of("ciao", "hello").<Integer>map(rethrowFunction(s -> transform(s))).collect(toList());
            assertEquals(2, sizes.size());
            assertEquals(4, sizes.get(0).intValue());
            assertEquals(5, sizes.get(1).intValue());
        }
    
        private Integer transform(String value) throws MyTestException {
            if(value==null) {
                throw new MyTestException();
            }
            return value.length();
        }
    
        private static class MyTestException extends Exception { }
    }
    
    0 讨论(0)
  • 2020-11-22 03:31

    I will do something generic:

    public interface Lambda {
    
        @FunctionalInterface
        public interface CheckedFunction<T> {
    
            T get() throws Exception;
        }
    
        public static <T> T handle(CheckedFunction<T> supplier) {
            try {
                return supplier.get();
            } catch (Exception exception) {
                throw new RuntimeException(exception);
    
            }
        }
    }
    

    usage:

     Lambda.handle(() -> method());
    
    0 讨论(0)
  • 2020-11-22 03:32
    public void frankTest() {
        int pageId= -1;
    
        List<Book> users= null;
        try {
            //Does Not Compile:  Object page=DatabaseConnection.getSpringConnection().queryForObject("SELECT * FROM bookmark_page", (rw, n) -> new Portal(rw.getInt("id"), "", users.parallelStream().filter(uu -> uu.getVbid() == rw.getString("user_id")).findFirst().get(), rw.getString("name")));
    
            //Compiles:
            Object page= DatabaseConnection.getSpringConnection().queryForObject("SELECT * FROM bookmark_page", (rw, n) -> { 
                try {
                    final Book bk= users.stream().filter(bp -> { 
                        String name= null;
                        try {
                            name = rw.getString("name");
                        } catch (Exception e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                        return bp.getTitle().equals(name); 
                    }).limit(1).collect(Collectors.toList()).get(0);
                } catch (Exception e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                return new Portal(rw.getInt("id"), "", users.get(0), rw.getString("name")); 
            } );
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    
    0 讨论(0)
提交回复
热议问题