To what extent should one make exceptions redundant or atomic to a method.For instance, suppose I have a method public void authenticate(String username, String password) that calls private void invokeServer(String username, String password).Both methods require those params to be non-zero length, and as such I would raise a NullPointerException if needed. Should I sanity check in invokeServer as well as authenticate on the basis that it could potentially be used independently at a later date?
Java exception redundancy
java;exceptions
First of all, non-empty and NullPointerException are two different beasts, so you should definitely not throw a NPE for a non-null empty string.In general, it makes sense to think about your exceptions on a higher level than just the null/non-empty-kind of level. In your case, you are taking about a username, or even more general, when you combine the two attributes you are talking about Login Credentials. And lo and behold, both of your methods in one way or another deal with login credentials, so a InvalidLoginCredentialsException or some such nicely fits both places (and probably others as well).When you think about the error cases from the viewpoint of your business or customers, by assigning use-cases or domains (or any fancy word like that, which is currently en vogue), then you should have a much easier time to deduce exceptions at a useful granularity level.