So, I'm working on designing a class wherein if certain arguments to certain methods are null, either the method (or the object as a whole) won't work.
I know that it'll throw a NullPointerException
once it receives the null object and attempts to use it, but I want the programmer trying to call the method to understand that the bug is not in my code. I just want to ensure that the resulting exception thrown would be very clear (without the need to look into my source).
I've seen a few examples of what I described, where they throw an IllegalArgumentException
when the parameter is null.
Here's the difference, imagine that someObject will somehow be vital to the method:
public void doSomething(SomeClass someObject) {
if (someObject == null) throw new IllegalArgumentException("someObject is null");
...
}
This way, the programmer understands that he or she has broken the contract implied by the javadoc (whether or not it is explicitly stated).
Is that good practice, or even a reasonable thing to do?
Quick Edit/Side-bar:
What would be best to say in the exception message?
Is it better to state what "went wrong":
someObject is null
Or is it better to state that something "went wrong" and generally imply the cause (and ultimately the solution):
someObject cannot be null
Or is there a better alternative?