Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to throw a null pointer exception and where [duplicate]

Tags:

java

exception

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);
}
like image 498
user1883212 Avatar asked Jan 23 '26 12:01

user1883212


1 Answers

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

like image 121
wero Avatar answered Jan 25 '26 01:01

wero



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!