7

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?

Akhil Sharma
  • 141
  • 2
  • 6
  • 1
    Do the failed records have anything in common which you could make in interface for? If not it might be wise to use different exception classes for higher maintainability. – Thomas Feb 04 '16 at 13:34
  • 1
    *"Or is there a better way?"* - No, there isn't. – Stephen C Feb 04 '16 at 13:50

1 Answers1

2

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

Community
  • 1
  • 1
Thomas Betous
  • 4,633
  • 2
  • 24
  • 45