Reputation: 851
I'm trying to test for null parameters but you cannot compare an object to null.
The following is dead code:
} else if(x == null){
throw new NullPointerException("Parameter is null");
}
How do I rewrite it to gain the desired effect?
Upvotes: 1
Views: 17628
Reputation: 31637
To use handle in the Java literal sense of the word
Foo foo = bar.couldReturnNull();
try {
foo.doSomething();
} catch (NullPointerException e) {
System.out.println("bar.couldReturnNull() returned null");
throw new NullPointerException();
}
Upvotes: 2
Reputation: 24316
In Java you can compare to the value null. The standard way to do this is as follows:
String s = null;
if(s == null)
{
//handle null
}
Typically throwing an NPE is a poor practice in the real world.
Upvotes: 4
Reputation: 2783
You don't say explicitly, but this looks like Java because of the NullPointerException. Yes, you can compare an object reference to null, and so this code is fine. You might be mixing it up with SQL, where nothing compares equal to null.
Upvotes: 1