【问题标题】:Generic list of Exception异常的通用列表
【发布时间】:2020-07-04 18:09:40
【问题描述】:

我想创建一个可以容纳不同类型异常的异常列表。我尝试了下面的代码,但它不起作用。有没有办法创建这样的列表?

List<? extends Exception> exceptions = new ArrayList<>();
        exceptions.add(RuntimeException.class);

【问题讨论】:

  • 这是一个不寻常的要求。我感觉到XY problem。你想完成什么?
  • 我正在尝试编写重试功能并想检查引发的异常是否是列表中的异常之一。如果是,则重试,否则不要。

标签: java exception arraylist


【解决方案1】:

如果你想保存异常类列表,那么你定义的列表不正确。

应该是

List<Class<? extends Exception>> exceptions = new ArrayList<>();

如果您想保存异常实例列表,那么通用通配符将不起作用。这是在泛型中使用通配符的一个缺点。您可以阅读有关限制的更多信息here

您可以像@slartidan 提到的那样简单地使用:

    List<Exception> myExceptionHolder = new ArrayList<>();
    myExceptionHolder.add(new RuntimeException());
    myExceptionHolder.add(new ArithmeticException());

    Assert.assertTrue(myExceptionHolder.get(0) instanceof RuntimeException );
    Assert.assertTrue(myExceptionHolder.get(1) instanceof ArithmeticException );

或者你可以有一个这样的类(如果你有一些其他复杂的用例):

public class MyExceptionHolder<T extends Exception> {
  private List<T> exceptions;

  public MyExceptionHolder() {
    this.exceptions = new ArrayList<>();
  }

  public List<T> getExceptions() {
    return new ArrayList<>(exceptions); //get a clone
  }

  public void addExceptions(T exception) {
    this.exceptions.add(exception);
  }
}

并使用它:

    MyExceptionHolder myExceptionHolder = new MyExceptionHolder();
    myExceptionHolder.addExceptions(new RuntimeException());
    myExceptionHolder.addExceptions(new ArithmeticException());

    List exs = myExceptionHolder.getExceptions();
    Assert.assertTrue(exs.get(0) instanceof RuntimeException );
    Assert.assertTrue(exs.get(1) instanceof ArithmeticException );

【讨论】:

  • 但是 MyExceptionHolder myExceptionHolder = new MyExceptionHolder(); 可以简化为 List&lt;Exception&gt; myExceptionHolder = new ArrayList&lt;&gt;(); - 没有任何通配符。并且代码运行良好。
  • 是的。它肯定会以更简单的方式用于保存所有类型的异常。
【解决方案2】:

如果您需要一个包含所有扩展异常的不同类的列表,那么您的意思可能是:

  List<Class<? extends Exception>> exceptions = new ArrayList<>();
    exceptions.add(RuntimeException.class);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-15
    • 1970-01-01
    • 2013-10-18
    • 2014-08-16
    • 2011-01-11
    • 1970-01-01
    相关资源
    最近更新 更多