Skip to content
gqlxj1987's Blog
Go back

Error Handling In Java Stream

Edit page

原文链接

static Consumer<String> exceptionHandledConsumer(Consumer<String> unhandledConsumer) {
    return obj -> {
        try {
            unhandledConsumer.accept(obj);
        } catch (NumberFormatException e) {
            System.err.println(
                    "Can't format this string");
        }
    };
}public static void main(String[] args) {
    List<String> integers = Arrays.asList("44", "xyz", "145");    integers.forEach(exceptionHandledConsumer(str -> System.out.println(Integer.parseInt(str))));
}

采用流式的处理方式,尽可能generics

进一步:

static <Target, ExObj extends Exception> Consumer<Target> handledConsumer(Consumer<Target> targetConsumer, Class<ExObj> exceptionClazz) {    return obj -> {
        try {
            targetConsumer.accept(obj);
        } catch (Exception ex) {
            try {
                ExObj exCast = exceptionClazz.cast(ex);
                System.err.println(
                        "Exception occured : " + exCast.getMessage());
            } catch (ClassCastException ccEx) {
                throw ex;
            }
        }
    };
}


List<String> integers = Arrays.asList("44", "373", "xyz", "145");integers.forEach(
        handledConsumer(str -> System.out.println(Integer.parseInt(str)), 
        NumberFormatException.class));

采用FunctionalInterface的方式,进一步提升,将函数提升到类?

@FunctionalInterface
public interface HandlingConsumer<Target, ExObj extends Exception> {
    void accept(Target target) throws ExObj;    static <Target> Consumer<Target> handlingConsumerBuilder(
            HandlingConsumer<Target, Exception> handlingConsumer) {        return obj -> {
            try {
                handlingConsumer.accept(obj);
            } catch (Exception ex) {
                throw new RuntimeException(ex);
            }
        };
    }
}

要经常性使用stream的方式,利用函数式的思路

多用lambda表达式


Edit page
Share this post on:

Previous Post
取舍
Next Post
JDTX distributed transaction midwares