Java 8 Lambda function that throws exception?

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

    Sneaky throw idiom enables bypassing CheckedException of Lambda expression. Wrapping a CheckedException in a RuntimeException is not good for strict error handling.

    It can be used as a Consumer function used in a Java collection.

    Here is a simple and improved version of jib's answer.

    import static Throwing.rethrow;
    
    @Test
    public void testRethrow() {
        thrown.expect(IOException.class);
        thrown.expectMessage("i=3");
    
        Arrays.asList(1, 2, 3).forEach(rethrow(e -> {
            int i = e.intValue();
            if (i == 3) {
                throw new IOException("i=" + i);
            }
        }));
    }
    

    This just wrapps the lambda in a rethrow. It makes CheckedException rethrow any Exception that was thrown in your lambda.

    public final class Throwing {
        private Throwing() {}
    
        @Nonnull
        public static  Consumer rethrow(@Nonnull final ThrowingConsumer consumer) {
            return consumer;
        }
    
        /**
         * The compiler sees the signature with the throws T inferred to a RuntimeException type, so it
         * allows the unchecked exception to propagate.
         * 
         * http://www.baeldung.com/java-sneaky-throws
         */
        @SuppressWarnings("unchecked")
        @Nonnull
        public static  void sneakyThrow(@Nonnull Throwable ex) throws E {
            throw (E) ex;
        }
    
    }
    

    Find a complete code and unit tests here.

提交回复
热议问题