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