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); } 
6
  • 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. Commented Oct 8, 2015 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. Commented Oct 8, 2015 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<String> for possibly missing values. So a javadoc comment would be entirely sufficient. Commented Oct 8, 2015 at 11:48
  • 1
    stackoverflow.com/questions/3322638/… check this link. Commented Oct 8, 2015 at 11:52
  • This does not seem to be a duplicate to me. Commented Oct 8, 2015 at 12:00

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

1 Comment

I just want to add that above code can be rewritten as Objects.requireNonNull(str,"str is null");

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.