Reputation: 29
I have created a custom exception and I want to throw an Exception which throws the exception with the list of integer. How do I do that? I know I can simple pass a message in Exception. But I want to pass a List as a Message in exception.
class HelloWorld {
public static void main(String[] args) {
List<Integer> invalidAges = new ArrayList<>();
for(int i = 0 ; i <10;i++) invalidAges.add(i);
throw new InvalidAgesException(invalidAges);
}
}
class InvalidAgesException extends RuntimeException {
private final List<Integer> invalidAges;
public InvalidAgesException(List<Integer> invalidAges) {
this.invalidAges = invalidAges;
}
public List<Integer> getInvalidAges() {
return invalidAges;
}
}
Output should be : Exception: [1,2,3,4,5,6,7,8,9,10]
Upvotes: 0
Views: 2864
Reputation: 5990
Your code here is fine, but I presume you're looking for the exception to actually print your list to the stack trace.
In this case you can just pass it to the constructor of RuntimeException
which accepts a String
as a message:
public InvalidAgesException(List<Integer> invalidAges) {
super(invalidAges.toString());
this.invalidAges = invalidAges;
}
Alternatively you can override the getMessage
method of the exception:
public String getMessage() {
return invalidAges.toString();
}
Upvotes: 1