I’m from a .NET background and now dabbling in Java.
Currently, I’m having big problems designing an API defensively against faulty input. Let’s say I’ve got the following code (close enough):
public void setTokens(Node node, int newTokens) {
tokens.put(node, newTokens);
}
However, this code can fail for two reasons:
null
node.In .NET, I would throw an ArgumentNullException
(rather than a NullReferenceException
!) or an ArgumentException
respectively, passing the name of the offending argument (node
) as a string
argument.
Java doesn’t seem to have equivalent exceptions. I realize that I could be more specific and just throw whatever exception comes closest to describing the situation, or even writing my own exception class for the specific situation.
Is this the best practice? Or are there general-purpose classes similar to ArgumentException
in .NET?
Does it even make sense to check against null
in this case? The code will fail anyway and the exception’s stack trace will contain the above method call. Checking against null
seems redundant and excessive. Granted, the stack trace will be slightly cleaner (since its target is the above method, rather than an internal check in the HashMap
implementation of the JRE). But this must be offset against the cost of an additional if
statement, which, furthermore, should never occur anyway – after all, passing null
to the above method isn’t an expected situation, it’s a rather stupid bug. Expecting it is downright paranoid – and it will fail with the same exception even if I don’t check for it.
[As has been pointed out in the comments, HashMap.put
actually allows null
values for the key. So a check against null
wouldn’t necessarily be redundant here.]
The standard Java exception is IllegalArgumentException
. Some will throw NullPointerException
if the argument is null, but for me NPE has that "someone screwed up" connotation, and you don't want clients of your API to think you don't know what you're doing.
For public APIs, check the arguments and fail early and cleanly. The time/cost barely matters.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With