@chetanaegis: I don't think there is a
num in the OP's code. And I wonder if the claim that it is
best to
always check explicitly for null might be a little extravagant. Sometimes if a variable is null, that indicates a real problem somewhere: a faulty assumption we have made. In short, a bug. Surrounding that bug in a protective if statement will just let it breed.
Rather, the bug ought to be found, caught and fixed. And sometimes that means a method like your doSomething() will do
absolutely nothing but throw a NullPointerException. And it needn't even do that explicitly, it might be enough to let the NPE happen as part of its normal operation. From doSomething()'s point of view there is little it can do (the problem occurred elsewhere) and little it ought to do (for fear of masking the problem).
To make this more concrete, I would code your example as:
/**
* Does something with a non zero integer.
* @param num the integer to which something is done
* @throws NullPointerException if the supplied argument is null
* @throws ArithmeticException if the supplied argument is zero
*/
public void doSomething(Integer num) {
// code here, eg
System.out.println(1 / num);
}
/**
* Does something with a non zero integer. If a null argument is used (or an argument with
* value zero) then 1 will be used.
* @param num the integer to which something is done
*/
public void doSomethingEx(Integer num) {
if(num == null || num == 0) {
num = new Integer(1);
}
// code here, eg
System.out.println(1 / num);
}
/**
* Sets some field to a non zero integer.
* @param num the value to be used
* @throws IllegalArgumentException if the supplied argument does not specify a nonzero integer
*/
public void setSomething(Integer num) {
if(num == null || num == 0) {
throw new IllegalArgumentException(
"setSomething() wants a nonzero integer, not " + num);
}
// code here, eg
myNum = num;
}
Mind the javadocs! Sometimes an explicit if statement is called for, sometimes not. (doSomethingEx() is a sort of middle ground where its debatable. Perhaps it makes the method unnecessarily complex.)
Our programs shouldn't be minefields with null pointer exceptions as something to be "avoided". When writing a program an NPE should be welcomed - as an old friend! - because of the information it, and its associated stack trace provides. This was the burden of my posts above.
@patrick.thomas58: On the contrary, if the results have displayed "successfully" (=="the OP saw the data he or she expected"), that would seem to give a clean bill of health to the getter methods that provided the information. (The OP did post that code.) Better, I think, to start by determining exactly what expression was null. (as in #4)
@world: NPE's are more like mayflies or wild flowers than they are like elephants. By those standards this thread is old. The original problem, defunct. (Cue, parrot.)