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:
- User passes a
null
node. - User passes an invalid node, i.e. one not contained in the graph.
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.]