1

guys. My question is simple. Can you help me what I do incorrect? I am trying to code smth like this, but got an error of compilation.

List<? extends Exception> exceptions = new ArrayList<BaseIRPMException>();
exceptions.add(new BaseException("Some text ");
  • Note that `List extends Exception> exceptions` can hold also something like `new ArrayList()`. In that case should `exceptions.add(new BaseException("Some text ");` compile fine? – Pshemo Aug 30 '21 at 14:25
  • How exactly are the classes `BaseIRPMException` and `BaseException` defined? What is their inheritance relationship? Do you have any JavaDoc for them? – julien.giband Aug 30 '21 at 14:25
  • In addition, it is worth noting that you can add a `BaseException` (or any subclass) to a regular `List`. Maybe that helps already. – Clashsoft Aug 30 '21 at 14:27
  • I mean the simplest situation. Let us call it `List extends Exception> exceptions = new ArrayList<>();` `exceptions.add(new BaseException("Some text "); ` – SimonNechypurenko Aug 30 '21 at 14:33
  • Lets rewrite your code a little. Should such code compile `public static void foo(List extends Exception> exceptions){ exceptions.add(new BaseException("Some text ")); }` ? Note that can be invoked with `foo(new ArrayList());` but also `foo(new List());`. – Pshemo Aug 30 '21 at 14:42
  • Also note that your example needs additional `)` at `exceptions.add(new BaseException("Some text ");` (before `;`) – Pshemo Aug 30 '21 at 14:49

1 Answers1

1

List<? extends Exception> means you have a List of some kind of exceptions but you don't know what kind of exceptions.

Because you don't know what kind of exceptions you need to insert, you cannot pass some special kind of exception to the list.

A List<? extends Exception> could be a List<IllegalArgumentException> and you cannot add a NullPointerException to such a list.

However, you can retrieve Exceptions from such a list.

As the compiler knows that your List contains some kind of Exception, elements, you can call .get() and assign the returned value to a variable of type Exception but you cannot assign it to a subtype because the compiler doesn't know the actual subtype.

If you want to create a list of subtypes of exceptions, you might want to use a List<Exception> as it also allows subtypes.

dan1st
  • 12,568
  • 8
  • 34
  • 67
  • In almost all of these sorts of cases, what the user really wants is just `List`, without the generic.s. Then any sort of Exception can be put in, and Exception can be taken out. The natural covariance of the class system is usually what people want. – markspace Aug 30 '21 at 15:13