When I have a potential null input... is it better to always check for it:
public void doSomething(String str) {
if (str == null)
throw new NullPointerException();
processData(str);
}
or pass on the invalid data, and wait for "processData()" to throw the nullPointerException:
public void doSomething(String str) {
processData(str);
}
This is opinionated, but imho it is better to throw it in the first layer:
If you got a stracktrace and see a NPE (deep down) inside a library implementation it is not clear if it was caused by a bug in the library or by your illegal argument.
For the same reason I would recommend to use a descriptive IllegalArgumentException instead of a NPE:
if (str == null)
throw new IllegalArgumentException("str is null");
(and give str a better name, too).
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