繁体   English   中英

在 Google Guava 中使用异常

[英]Using exceptions with Google Guava

将 Google Guava 与应该抛出异常的方法一起使用的最佳模式是什么?

假设我有:

public Sting someMethod(Integer i) throws SomeException;

我想做:

List<String> s=Lists.transform(is,new Function<String, Integer>() {
       public String apply(Integer i) {
         return someMethod(i);
       }
     });

由于异常,我无法执行上述操作。 有什么好的处理方式吗?

将已检查的异常作为 RuntimeException 传播:

try {
    return someMethod(i);
} catch (SomeException e) {
    throw new RuntimeException(e);
}

编辑:由于转换后的列表是惰性计算的,因此在您访问列表元素之前不会抛出异常。 您可以通过将转换后的列表复制到新列表中来强制评估,例如:

s = new ArrayList<>(s);

您可以将它包装在一个 try-catch 块中,该块捕获 RuntimeException 并根据需要对其进行处理; 您可以通过在 RuntimeException 上调用 getCause() 来获取原始 SomeException 实例。 或者你可以让 RuntimeException 冒泡。

您可以使用

public interface FunctionWithException<T, R, E extends Exception> {
    public R apply(T t) throws E;
}

这取决于您想如何处理异常。

  1. 发生异常时停止列表转换:请参阅@dnault 的回答。
  2. 继续列表转换并删除导致异常的元素(并记录一些错误消息)。 在这种情况下,当发生异常时我们将返回 null,这个 null 值将从最终列表中删除:

     List<String> s = Lists.newArrayList( Iterables.filter( Iterables.transform(l, new Function<Integer, String>() { @Override public String apply(Integer i) { try { return someMethod(i); } catch (SomeException e) { e.printStackTrace(); return null; } } }), Predicates.notNull()))`

编辑如果 someMethod 可以返回空值,那么你应该像这样一个包装器:

class Wrapper {
    public Exception exception = null;
    public String result = null;
}

列表转换将是:

    List<Wrapper> wrappers = Lists.newArrayList(
            Iterables.filter(
            Iterables.transform(l, new Function<Integer, Wrapper>() {
               @Override
               public Wrapper apply(Integer i) {
                  Wrapper wrapper = new Wrapper();
                  try {
                    wrapper.result = someMethod(i);
                  } catch (SomeException e) {
                    wrapper.exception = e;
                  }
                  return wrapper;
                }
             }), new Predicate<Wrapper>() {
                @Override
                public boolean apply(Wrapper wrapper) {
                    return wrapper.exception == null;
                }
            }));

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM