Reputation: 57
Lets say I have a method combine
T[] combine(T[] arr1, T[] arr2, Comparator<T> cmp, Class<?> type) throws IllegalArgumentException{
...
}
And inside that I want to create an array using reflection. T[] newArray = (T[]) Array.newInstance(type, arr1.length+arr2.length);
. If an error accors during initializing newArray
I want to throw new IllegalArgumentExeption()
.
How should I do this preferably? Can I do this with try and catch blocks? Inside the try block I would try to initialize the array and inside the catch I would throw the IllegalArgumentEception.
Upvotes: 0
Views: 71
Reputation: 131326
You could do as you suppose but I would be careful about two points :
catching any exception and not a specific exception
throwing the IllegalArgumentException
by wrapping the caught exception. Having the full stracktrace may help to debug
For example :
try{
...
}
catch (Exception e){
throw new IllegalArgumentException("exception during combine() invocation with params..." , e);
}
Note that declaring throws IllegalArgumentException
in the method declaration is really not required as the client doesn't have any constraint to handle it : it is a RuntimeException
.
It is like declaring throws NullPointerException
for a method that can throw it.
If you want to constraint clients to handle the exception, use rather a checked Exception
.
Upvotes: 2