Illegalargumentexception or Nullpointerexception For a Null Parameter

IllegalArgumentException or NullPointerException for a null parameter?

It seems like an IllegalArgumentException is called for if you don't want null to be an allowed value, and the NullPointerException would be thrown if you were trying to use a variable that turns out to be null.

Java/Guava: handle 'null' arguments. Which exception?

There is no right way. Some people argue NPE since you passed a null pointer. Plus you can directly use Preconditions.checkNotNull() without any additional checks in code that you have to write (!=null is another 6-10 key presses, after all, plus people have to read more code to understand what you're doing).

Preconditions.checkArgument() makes more sense from an API point of view since the method doesn't want null arguments. Plus you have additional code to write and to read when you're debugging.

Verifify seems too weak for this for me, after reading the documentation.

Avoiding NullPointerException in Java

This to me sounds like a reasonably common problem that junior to intermediate developers tend to face at some point: they either don't know or don't trust the contracts they are participating in and defensively overcheck for nulls. Additionally, when writing their own code, they tend to rely on returning nulls to indicate something thus requiring the caller to check for nulls.

To put this another way, there are two instances where null checking comes up:

  1. Where null is a valid response in terms of the contract; and

  2. Where it isn't a valid response.

(2) is easy. As of Java 1.7 you can use Objects.requireNonNull(foo). (If you are stuck with a previous version then assertions may be a good alternative.)

"Proper" usage of this method would be like below. The method returns the object passed into it and throws a NullPointerException if the object is null. This means that the returned value is always non-null. The method is primarily intended for validating parameters.

public Foo(Bar bar) {
this.bar = Objects.requireNonNull(bar);
}

It can also be used like an assertion though since it throws an exception if the object is null. In both uses, a message can be added which will be shown in the exception. Below is using it like an assertion and providing a message.

Objects.requireNonNull(someobject, "if someobject is null then something is wrong");
someobject.doCalc();

Generally throwing a specific exception like NullPointerException when a value is null but shouldn't be is favorable to throwing a more general exception like AssertionError. This is the approach the Java library takes; favoring NullPointerException over IllegalArgumentException when an argument is not allowed to be null.

(1) is a little harder. If you have no control over the code you're calling then you're stuck. If null is a valid response, you have to check for it.

If it's code that you do control, however (and this is often the case), then it's a different story. Avoid using nulls as a response. With methods that return collections, it's easy: return empty collections (or arrays) instead of nulls pretty much all the time.

With non-collections it might be harder. Consider this as an example: if you have these interfaces:

public interface Action {
void doSomething();
}

public interface Parser {
Action findAction(String userInput);
}

where Parser takes raw user input and finds something to do, perhaps if you're implementing a command line interface for something. Now you might make the contract that it returns null if there's no appropriate action. That leads the null checking you're talking about.

An alternative solution is to never return null and instead use the Null Object pattern:

public class MyParser implements Parser {
private static Action DO_NOTHING = new Action() {
public void doSomething() { /* do nothing */ }
};

public Action findAction(String userInput) {
// ...
if ( /* we can't find any actions */ ) {
return DO_NOTHING;
}
}
}

Compare:

Parser parser = ParserFactory.getParser();
if (parser == null) {
// now what?
// this would be an example of where null isn't (or shouldn't be) a valid response
}
Action action = parser.findAction(someInput);
if (action == null) {
// do nothing
} else {
action.doSomething();
}

to

ParserFactory.getParser().findAction(someInput).doSomething();

which is a much better design because it leads to more concise code.

That said, perhaps it is entirely appropriate for the findAction() method to throw an Exception with a meaningful error message -- especially in this case where you are relying on user input. It would be much better for the findAction method to throw an Exception than for the calling method to blow up with a simple NullPointerException with no explanation.

try {
ParserFactory.getParser().findAction(someInput).doSomething();
} catch(ActionNotFoundException anfe) {
userConsole.err(anfe.getMessage());
}

Or if you think the try/catch mechanism is too ugly, rather than Do Nothing your default action should provide feedback to the user.

public Action findAction(final String userInput) {
/* Code to return requested Action if found */
return new Action() {
public void doSomething() {
userConsole.err("Action not found: " + userInput);
}
}
}

Choosing between NullPointerException and IllegalArgumentException for signalling error at object construction

IllegalArgument makes it clear, to the developer who's used the code, what the problem is and how to fix it I would say. It also makes it clear that the method CANNOT work without that object.

NullPointer means they have to think a little bit about what the problem is (not much) and may mean the code is cleaner, but like I said above. It's not immediately clear, from a documentation point-of-view whether your code can work with a null value or not.

IllegalArgumentException: Parameter specified as non-null is null

The exception is pretty clear: you're passing null for the parameter.

By default all variables and parameters in Kotlin are non-null. If you want to pass null parameter to the method you should add ? to it's type, for example:

fun fetchMerchantHashes(intent: Intent?)

For more information: null-safety.

IllegalArgumentException or NullPointerException for a null parameter?

It seems like an IllegalArgumentException is called for if you don't want null to be an allowed value, and the NullPointerException would be thrown if you were trying to use a variable that turns out to be null.

Is it okay to throw NullPointerException programmatically?

I see no problem with throwing a NPE as early as possible before the JVM does it for you - in particular for null arguments. There seems to be some debate about this, but there are many examples in the Java SE libraries that does exactly this. I cannot see why NPE should be holy in the aspect that you are not able to throw it yourself.

However, I digress. This question is about something different. You are talking about a post-condition stating that the return value mustn't be null. Surely null in this case would mean you have a bug inside the very method?

How would you even document this? "This method throws a NullPointerException if the return value unexpectedly is null"? Without explaining how this could happen? No, I would use an assertion here. Exceptions should be used for errors that can conceivably happen - not to cover things that can happen if there's something wrong inside the method, because that does not help anybody.



Related Topics



Leave a reply



Submit