3

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);
}
user1883212
  • 7,539
  • 11
  • 46
  • 82
  • it depends - if processData is an internal function (not accessible as a public interface), it might not do a null pointer check. Even if it does, it depends if you have code before processData that needs to run. – ronalchn Oct 08 '15 at 11:44
  • I think, need to check first, if not NULL then pass ahead. so that in future any further modification comes on other module not get affected by null pointer. – Vishal Gajera Oct 08 '15 at 11:47
  • 1
    There are also some annotations for non-null parameters. But the trend seems that non-null is in general assumed. In java 8 use `Optional` for possibly missing values. So a javadoc comment would be entirely sufficient. – Joop Eggen Oct 08 '15 at 11:48
  • 1
    http://stackoverflow.com/questions/3322638/is-it-okay-to-throw-nullpointerexception-programatically check this link. – Shiladittya Chakraborty Oct 08 '15 at 11:52
  • This does not seem to be a duplicate to me. – wero Oct 08 '15 at 12:00
  • @wero For me both discussions ware close enough but I could be wrong. You can vote to reopen if you wish. – Pshemo Oct 08 '15 at 12:03

1 Answers1

6

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).

wero
  • 32,544
  • 3
  • 59
  • 84
  • 1
    I just want to add that above code can be rewritten as `Objects.requireNonNull(str,"str is null");` – Pshemo Oct 08 '15 at 11:52