Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom Exception with generic type [duplicate]

I have wrapped the Exception in my java class into a custom exception. I want my custom exception to receive two parameters, one the message and second a list.

But the problem is listOfFailedRecords has to be generic.

Something like,

throw new MyException("Failed due to dependency", listOfFailedRecords)

And the MyException class would look like,

public class MyException<T> extends Exception {
    List<T> listOfFailedRecords;
    MyException(String message, List<T> listOfFailedRecords) {
        super(message);
        this.listOfFailedRecords = listOfFailedRecords;
    }
}

But the problem is Java doesn't allow generic class to extend Exception class.

What should be the approach now? Should I pass a list of Objects to this exception as

List<Object> listOfFailedRecords

Or is there a better way?

like image 338
Akhil Sharma Avatar asked Feb 04 '16 13:02

Akhil Sharma


1 Answers

You should probably use an interface to group the behaviour of your failed records. If there is a specific reason you can't do it, it is likely you have a problem with your design. In this case, you should make several exception classes.

Here is a good post to understand why Java doesn't allow subclasses of throwable : https://stackoverflow.com/a/501309/3425744

like image 68
Thomas Betous Avatar answered Sep 19 '22 10:09

Thomas Betous