代码之家  ›  专栏  ›  技术社区  ›  user10367961

处理Java8流[duplicate]中已检查的异常

  •  4
  • user10367961  · 技术社区  · 7 年前

    假设您有一个第三方库,它公开了下一个接口。

    interface Mapper {
    
        String doMap(String input) throws CheckedException;
    
    }
    
    class CheckedException extends Exception {
    
    }
    

    我想结合Java8 streams API使用Mapper接口的实现。考虑下面的示例实现。

    class MapperImpl implements Mapper {
    
        public String doMap(String input) throws CheckedException {
            return input;
        }
    
    }
    

    现在,我想将映射器应用到一个字符串集合,例如。

    public static void main(String[] args) {
        List<String> strings = Arrays.asList("foo", "bar", "baz");
        Mapper mapper = new MapperImpl();
    
        List<String> mappedStrings = strings
                .stream()
                .map(mapper::doMap)
                .collect(Collectors.toList());
    }
    

    代码无法编译,因为函数不知道如何处理doMap声明的CheckedException。我想出了两个可能的解决办法。

    解决方案#1-包装调用

    .map(value -> {
                    try {
                        return mapper.doMap(value);
                    } catch (CheckedException e) {
                        throw new UncheckedException();
                    }
                })
    

    public static final String uncheck (Mapper mapper, String input){
        try {
            return mapper.doMap(input);
        } catch (CheckedException e){
            throw new UncheckedException();
        }
    }
    

    然后我可以用

    .map(value -> Utils.uncheck(mapper, value))
    

    谢谢!

    2 回复  |  直到 7 年前
        1
  •  3
  •   Alex Shesterov    7 年前

    你基本上列出了两个可行的选择。

    还有一个选择是 使选中的异常从流处理函数中抛出 (“传播”或“隐藏”选中的异常)。这是通过捕获选中的异常并将其作为 RuntimeException (通过铸造)。看一看 this great answer 详情。

    例如,您可以查看NoException库: https://noexception.machinezoo.com/

    例如,在您的情况下:

    .map(value -> Exceptions.sneak().function(mapper::doMap))
    

    .map(value -> Exceptions.wrap().function(mapper::doMap))
    

    附言:我不是这个图书馆的作者,也不是一个贡献者,但我在几个项目中使用过这个图书馆。

        2
  •  1
  •   Matthieu Gabin    7 年前

    faux-pas 这简化了Java函数式编程的错误处理。我认为在流中管理检查异常非常好。