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
A nullpointerexception usually indicates a programmer error. You won’t catch a null pointer exception if you don’t expect such a programmer error. For instance, say you implement a method myMethod with one parameter of type P.
Let’s say you don’t expect the parameter x to be null. In this case you might not check for null. Why? because you assume that the programmer who is using your method will use it properly and won’t pass null. I’m not saying whether you should or shouldn’t check for null in such cases. I’m just trying to answer why sometimes a null pointer exception is thrown by a method and isn’t supposed to be caught. Here’s why: Your method might throw a null pointer exception because someone didn’t use it right (passed null). The programmer who is using your method might know that if the method is being used wrong it might throw a nullpointerexcetption. But even if he uses your method wrong the exception won’t be caught because everyone assumes that the method isn’t misused.
Your second question: First, a String is an Object, not a primitive type. Second, primitives can’t be null (primitives are ints, doubles, floats, chars, booleans and some others). Now, if you encounter a parameter which is null and it shouldn’t be null (in other words you received an illegal argument) you have some choices:
assert(x != null);I personally am not a fan of defensive programming and usually prefer the second option. But still, if I want to ensure some invariants on my variables I’m using assertions. But these are just my habits and others probably disagree.