1

I want to create a list of exception which can hold different type of exception. I tried below code but it is not working. Is there a way to create such list ?

List<? extends Exception> exceptions = new ArrayList<>();
        exceptions.add(RuntimeException.class);
BobCoder
  • 743
  • 2
  • 10
  • 27
  • This is an unusual thing to ask for. I sense an [XY problem](https://meta.stackexchange.com/questions/66377/what-is-the-xy-problem/66378#66378). What are you trying to accomplish? – VGR Jul 05 '20 at 00:16
  • I'm trying to write a retry functionality and want to check if exception raised is one of the exception from list. If yes then retry else don't. – BobCoder Jul 05 '20 at 17:18

2 Answers2

0

if you need a list that holds different classes that all extends Exception, then you probably you mean this:

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

If you want to hold list of exception classes, then you have defined the list incorrectly.

It should be

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

If you want to hold list of exception instances, then Generic Wildcards wont work. This is a drawback of using wildcards in Generics. You can read more about the limitations here.

You can simply use as @slartidan mentioned:

    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 );

Or you can have a class like this (if you have some other complex use case):

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);
  }
}

and to use it:

    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 );
Abhinaba Chakraborty
  • 3,488
  • 2
  • 16
  • 37
  • But `MyExceptionHolder myExceptionHolder = new MyExceptionHolder();` could be simplified to `List myExceptionHolder = new ArrayList<>();` - without any wildcards. And the code would run fine. – slartidan Jul 04 '20 at 18:47
  • True. It will definitely serve the purpose of holding all types of Exceptions and in much simpler way. – Abhinaba Chakraborty Jul 04 '20 at 19:10