Java 8 Lambda function that throws exception?

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

    I'm the author of a tiny lib with some generic magic to throw any Java Exception anywhere without the need of catching them nor wrapping them into RuntimeException.

    Usage: unchecked(() -> methodThrowingCheckedException())

    public class UncheckedExceptions {
    
        /**
         * throws {@code exception} as unchecked exception, without wrapping exception.
         *
         * @return will never return anything, return type is set to {@code exception} only to be able to write throw unchecked(exception)
         * @throws T {@code exception} as unchecked exception
         */
        @SuppressWarnings("unchecked")
        public static  T unchecked(Exception exception) throws T {
            throw (T) exception;
        }
    
    
        @FunctionalInterface
        public interface UncheckedFunction {
            R call() throws Exception;
        }
    
        /**
         * Executes given function,
         * catches and rethrows checked exceptions as unchecked exceptions, without wrapping exception.
         *
         * @return result of function
         * @see #unchecked(Exception)
         */
        public static  R unchecked(UncheckedFunction function) {
            try {
                return function.call();
            } catch (Exception e) {
                throw unchecked(e);
            }
        }
    
    
        @FunctionalInterface
        public interface UncheckedMethod {
            void call() throws Exception;
        }
    
        /**
         * Executes given method,
         * catches and rethrows checked exceptions as unchecked exceptions, without wrapping exception.
         *
         * @see #unchecked(Exception)
         */
        public static void unchecked(UncheckedMethod method) {
            try {
                method.call();
            } catch (Exception e) {
                throw unchecked(e);
            }
        }
    }
    

    source: https://github.com/qoomon/unchecked-exceptions-java

提交回复
热议问题