Consider the below method-
public void operationOnList(List<String> list) {
list.add(1);
}
It is obvious that if list is null this method will throw a NullPointerException.
My question is should I instead check for null explicitly in this case?
public void operationOnList(List<String> list) {
if (list == null) throw new NullPointerException("some message")
list.add(1);
}
On one had I can add a message here, but what if I am not really concerned about the message? It helps me save an unnecessary branching in the code.
So which is preferable and which is more efficient?
EDIT - it is not a duplicate : In my case, the method will throw a NullPointerException if you pass a null to it in BOTH the above cases. I don't want or need to handle the exception and resolve it in the function.
What I am asking is should I check for null explicitly (adding unnecessary if condition or should I let the NPE occur when that variable is used?
Edit: -------------------------------------
A few thoughts over time:
- If the method is exposed to client i.e. it is part of some api, it is a good idea to check as early as possible to check for the exception and throw an NPE with a good message. The reason being if the NPE gets thrown from further inside, an ugly stack trace gets printed, and user might not immediately know which method is the culprit.