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