Home > OS >  Java generics: getting a subclass of Exception
Java generics: getting a subclass of Exception

Time:12-18

ive been learning java recently and got to generics and exceptions i have multiple classes that extend Exception as i need a bunch of custom exception in my project for example the FileEmptyException:

and i also have an ExceptionHandler class

public class FileEmptyException extends Exception {


public FileEmptyException() {
    super();
    // TODO Auto-generated constructor stub
}

}

 public class ExceptionHandler<Ex extends Exception> {



List<Ex> ls;



public ExceptionHandler()
{
    
    ls = new ArrayList<>();
}
public void addException(Ex ex)
{
    ls.add(ex);
}

}

when i try to make an instance of my ExceptionHandler object and add the custom exception to the list, i encounter the compilation error "The method addException(capture#1-of ? extends Exception) in the type ExceptionHandler<capture#1-of ? extends Exception> is not applicable for the arguments (FileNotFoundException)"

i instantiated the object the following way:

private ExceptionHandler<? extends Exception> EH = new ExceptionHandler<>();

and called the function the following way:

        if(!s.hasNext())
        EH.addException(new FileEmptyException());

my main question is if what im trying to do is even possible(i assume yes) and if so what would be the correct way?

thanks in advance and sorry for my own ignorance!

CodePudding user response:

The correct way of expressing what you actually want to express in this case is to write ExceptionHandler<Exception>, not ExceptionHandler<? extends Exception>.

You may conclude from this that ExceptionHandler shouldn't be generic, and should just have a List<Exception>. That's up to your use case.

  • Related