Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best practise in catching and throwing nullpointerexception?

It seems like it is not a good idea to catch a nullpointerexception. If that's the case, why is it thrown by methods? Should it just be caught with Exception?

Also, if I encounter a parameter which is null (can either be primitive type like string or a class with fields), how should I handle it? (assumingly not throw npe)?

Thanks

like image 761
GurdeepS Avatar asked Jan 17 '11 16:01

GurdeepS


1 Answers

It is a runtime exception, thus is not intended to be caught deep inside your program code, only [update] at (or close to) the top level or [/update] by the JVM. Since runtime exceptions signal serious problems (typically grave programming errors, configuration/integration problems etc.), it is best to let them propagate to the top, which typically makes the whole thread fail spectacularly. This gives a strong signal that something is wrong and needs to be fixed ASAP.

See also Is Catching a Null Pointer Exception a Code Smell?.

Also, if I encounter a parameter which is null [...], how should I handle it?

It is OK to throw a NPE in general. However, depending on the circumstances, you may also consider IllegalArgumentException, or using an assertion. See also

  • Is it okay to throw NullPointerException programatically ?
  • IllegalArgumentException or NullPointerException for a null parameter?
like image 78
Péter Török Avatar answered Oct 04 '22 03:10

Péter Török