How to notify the programmer of a null argument? - java

So, I'm working on designing a class wherein if certain arguments to certain methods are null, either the method (or the object as a whole) won't work.
I know that it'll throw a NullPointerException once it receives the null object and attempts to use it, but I want the programmer trying to call the method to understand that the bug is not in my code. I just want to ensure that the resulting exception thrown would be very clear (without the need to look into my source).
I've seen a few examples of what I described, where they throw an IllegalArgumentException when the parameter is null.
Here's the difference, imagine that someObject will somehow be vital to the method:
public void doSomething(SomeClass someObject) {
if (someObject == null) throw new IllegalArgumentException("someObject is null");
...
}
This way, the programmer understands that he or she has broken the contract implied by the javadoc (whether or not it is explicitly stated).
Is that good practice, or even a reasonable thing to do?
Quick Edit/Side-bar:
What would be best to say in the exception message?
Is it better to state what "went wrong":
someObject is null
Or is it better to state that something "went wrong" and generally imply the cause (and ultimately the solution):
someObject cannot be null
Or is there a better alternative?

Use an IllegalArgumentException instead of allowing the NullPointerException so that you can discover the error as early as possible. You could perform the same check and throw a NullPointerException yourself as well, but that's a matter of semantics.
By throwing the error immediately, it helps you or some other developer catch the mistake before anything else happens. If your method doesn't use the argument immediately (for instance, in a setter), then the problem could appear to be the result of some completely different operation.
If you're not familiar with it, a fantastic book called The Pragmatic Programmer has a tip that I'm trying to emphasize here:
Time 32: Crash Early
The main idea is to fail before anything bad can happen, rather than allow problems to crop up at unexpected times.
This would also be a good place to use an assertion to enforce your precondition. Make sure you document that the argument cannot be null, and make your method look like this:
public void doSomething(SomeClass someObject) {
assert someObject != null
...
}
If the assertion fails, an error will be thrown. While this could be turned off with compiler options, it's a good practice during development.

I would say the standard, documented practice is to just use NullPointerException.
It is used explicitly in many #throws Javadocs to document the case when an argument is null and is not allowed to be (Reader.read(CharBuffer), String.contains(CharSequence) and many, many more)
It is recommended in respected coding guidelines (for example, Bloch recommends its use in Effective Java).
The class itself says that it's meant to be thrown explicitly:
Applications should throw instances of this class to indicate other illegal uses of the null object.
It's what Guava's Preconditions throw for checkNotNull, and they know Java library design.
Using a NullPointerException doesn't prevent you from giving a good error message describing the exception. By doing so you would set such stacktraces apart from the default NPE stacktrace.
If you really want to deviate from the standard, you can use IllegalArgumentException but at that point I'd go one further and create a subclass called NullArgumentException.
Edit
Speaking of Preconditions, you seem on track to be using runtime exceptions effectively for checking values and invariants. I highly recommend you just use Guava's Preconditions library to standardize and simplify this. Your example would just boil down to:
public void doSomething(SomeClass someObject) {
Preconditions.checkNotNull(someObject, "someObject cannot be null");
//...
}

You can use either. Just document your choice and be consistent. If clients are likely to use your library with another, being consistent with that will likely help clients as well.

Both approaches are reasonable. If your javadoc says that passing a null will result in a NPE, and the user of your API gets a NPE, then it sounds to me like the function is working as advertised!
I find that a NPE is easiest when the argument is to be used in that method. If you're going to be saving the reference for later (e.g., in a constructor), then the IllegalArgumentException makes a bit more sense. In other words, throw a NPE if that comes naturally, and throw an IAE if it saves a future NPE.

I prefer using NPE, but I would validate the input in the beginning of the method, because otherwise my object's state can be changed to something illegal (because of some non-complete work).

Related

Findbug telling me not to throw NullPointerException [duplicate]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 6 years ago.
Improve this question
I have a simple setter method for a property and null is not appropriate for this particular property. I have always been torn in this situation: should I throw an IllegalArgumentException, or a NullPointerException? From the javadocs, both seem appropriate. Is there some kind of an understood standard? Or is this just one of those things that you should do whatever you prefer and both are really correct?
You should be using IllegalArgumentException (IAE), not NullPointerException (NPE) for the following reasons:
First, the NPE JavaDoc explicitly lists the cases where NPE is appropriate. Notice that all of them are thrown by the runtime when null is used inappropriately. In contrast, the IAE JavaDoc couldn't be more clear: "Thrown to indicate that a method has been passed an illegal or inappropriate argument." Yup, that's you!
Second, when you see an NPE in a stack trace, what do you assume? Probably that someone dereferenced a null. When you see IAE, you assume the caller of the method at the top of the stack passed in an illegal value. Again, the latter assumption is true, the former is misleading.
Third, since IAE is clearly designed for validating parameters, you have to assume it as the default choice of exception, so why would you choose NPE instead? Certainly not for different behavior -- do you really expect calling code to catch NPE's separately from IAE and do something different as a result? Are you trying to communicate a more specific error message? But you can do that in the exception message text anyway, as you should for all other incorrect parameters.
Fourth, all other incorrect parameter data will be IAE, so why not be consistent? Why is it that an illegal null is so special that it deserves a separate exception from all other types of illegal arguments?
Finally, I accept the argument given by other answers that parts of the Java API use NPE in this manner. However, the Java API is inconsistent with everything from exception types to naming conventions, so I think just blindly copying (your favorite part of) the Java API isn't a good enough argument to trump these other considerations.
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.
The standard is to throw the NullPointerException. The generally infallible "Effective Java" discusses this briefly in Item 42 (first edition), Item 60 (second edition), or Item 72 (third edition) "Favor the use of standard exceptions":
"Arguably, all erroneous method
invocations boil down to an illegal
argument or illegal state, but other
exceptions are standardly used for
certain kinds of illegal arguments and
states. If a caller passes null in
some parameter for which null values
are prohibited, convention dictates
that NullPointerException be thrown
rather than IllegalArgumentException."
I was all in favour of throwing IllegalArgumentException for null parameters, until today, when I noticed the java.util.Objects.requireNonNull method in Java 7. With that method, instead of doing:
if (param == null) {
throw new IllegalArgumentException("param cannot be null.");
}
you can do:
Objects.requireNonNull(param);
and it will throw a NullPointerException if the parameter you pass it is null.
Given that that method is right bang in the middle of java.util I take its existence to be a pretty strong indication that throwing NullPointerException is "the Java way of doing things".
I think I'm decided at any rate.
Note that the arguments about hard debugging are bogus because you can of course provide a message to NullPointerException saying what was null and why it shouldn't be null. Just like with IllegalArgumentException.
One added advantage of NullPointerException is that, in highly performance critical code, you could dispense with an explicit check for null (and a NullPointerException with a friendly error message), and just rely on the NullPointerException you'll get automatically when you call a method on the null parameter. Provided you call a method quickly (i.e. fail fast), then you have essentially the same effect, just not quite as user friendly for the developer. Most times it's probably better to check explicitly and throw with a useful message to indicate which parameter was null, but it's nice to have the option of changing that if performance dictates without breaking the published contract of the method/constructor.
I tend to follow the design of JDK libraries, especially Collections and Concurrency (Joshua Bloch, Doug Lea, those guys know how to design solid APIs). Anyway, many APIs in the JDK pro-actively throws NullPointerException.
For example, the Javadoc for Map.containsKey states:
#throws NullPointerException if the key is null and this map
does not permit null keys (optional).
It's perfectly valid to throw your own NPE. The convention is to include the parameter name which was null in the message of the exception.
The pattern goes:
public void someMethod(Object mustNotBeNull) {
if (mustNotBeNull == null) {
throw new NullPointerException("mustNotBeNull must not be null");
}
}
Whatever you do, don't allow a bad value to get set and throw an exception later when other code attempts to use it. That makes debugging a nightmare. You should always the follow the "fail-fast" principle.
Voted up Jason Cohen's argument because it was well presented. Let me dismember it step by step. ;-)
The NPE JavaDoc explicitly says, "other illegal uses of the null object". If it was just limited to situations where the runtime encounters a null when it shouldn't, all such cases could be defined far more succinctly.
Can't help it if you assume the wrong thing, but assuming encapsulation is applied properly, you really shouldn't care or notice whether a null was dereferenced inappropriately vs. whether a method detected an inappropriate null and fired an exception off.
I'd choose NPE over IAE for multiple reasons
It is more specific about the nature of the illegal operation
Logic that mistakenly allows nulls tends to be very different from logic that mistakenly allows illegal values. For example, if I'm validating data entered by a user, if I get value that is unacceptable, the source of that error is with the end user of the application. If I get a null, that's programmer error.
Invalid values can cause things like stack overflows, out of memory errors, parsing exceptions, etc. Indeed, most errors generally present, at some point, as an invalid value in some method call. For this reason I see IAE as actually the MOST GENERAL of all exceptions under RuntimeException.
Actually, other invalid arguments can result in all kinds of other exceptions. UnknownHostException, FileNotFoundException, a variety of syntax error exceptions, IndexOutOfBoundsException, authentication failures, etc., etc.
In general, I feel NPE is much maligned because traditionally has been associated with code that fails to follow the fail fast principle. That, plus the JDK's failure to populate NPE's with a message string really has created a strong negative sentiment that isn't well founded. Indeed, the difference between NPE and IAE from a runtime perspective is strictly the name. From that perspective, the more precise you are with the name, the more clarity you give to the caller.
It's a "Holy War" style question. In others words, both alternatives are good, but people will have their preferences which they will defend to the death.
If it's a setter method and null is being passed to it, I think it would make more sense to throw an IllegalArgumentException. A NullPointerException seems to make more sense in the case where you're attempting to actually use the null.
So, if you're using it and it's null, NullPointer. If it's being passed in and it's null, IllegalArgument.
Apache Commons Lang has a NullArgumentException that does a number of the things discussed here: it extends IllegalArgumentException and its sole constructor takes the name of the argument which should have been non-null.
While I feel that throwing something like a NullArgumentException or IllegalArgumentException more accurately describes the exceptional circumstances, my colleagues and I have chosen to defer to Bloch's advice on the subject.
As a subjective question this should be closed, but as it's still open:
This is part of the internal policy used at my previous place of employment and it worked really well. This is all from memory so I can't remember the exact wording. It's worth noting that they did not use checked exceptions, but that is beyond the scope of the question. The unchecked exceptions they did use fell into 3 main categories.
NullPointerException: Do not throw intentionally. NPEs are to be thrown only by the VM when dereferencing a null reference. All possible effort is to be made to ensure that these are never thrown. #Nullable and #NotNull should be used in conjunction with code analysis tools to find these errors.
IllegalArgumentException: Thrown when an argument to a function does not conform to the public documentation, such that the error can be identified and described in terms of the arguments passed in. The OP's situation would fall into this category.
IllegalStateException: Thrown when a function is called and its arguments are either unexpected at the time they are passed or incompatible with the state of the object the method is a member of.
For example, there were two internal versions of the IndexOutOfBoundsException used in things that had a length. One a sub-class of IllegalStateException, used if the index was larger than the length. The other a subclass of IllegalArgumentException, used if the index was negative. This was because you could add more items to the object and the argument would be valid, while a negative number is never valid.
As I said, this system works really well, and it took someone to explain why the distinction is there: "Depending on the type of error it is quite straightforward for you to figure out what to do. Even if you can't actually figure out what went wrong you can figure out where to catch that error and create additional debugging information."
NullPointerException: Handle the Null case or put in an assertion so that the NPE is not thrown. If you put in an assertion is just one of the other two types. If possible, continue debugging as if the assertion was there in the first place.
IllegalArgumentException: you have something wrong at your call site. If the values being passed in are from another function, find out why you are receiving an incorrect value. If you are passing in one of your arguments propagate the error checks up the call stack until you find the function that is not returning what you expect.
IllegalStateException: You have not called your functions in the correct order. If you are using one of your arguments, check them and throw an IllegalArgumentException describing the issue. You can then propagate the cheeks up against the stack until you find the issue.
Anyway, his point was that you can only copy the IllegalArgumentAssertions up the stack. There is no way for you to propagate the IllegalStateExceptions or NullPointerExceptions up the stack because they had something to do with your function.
Couldn't agree more with what's being said. Fail early, fail fast. Pretty good Exception mantra.
The question about which Exception to throw is mostly a matter of personal taste. In my mind IllegalArgumentException seems more specific than using a NPE since it's telling me that the problem was with an argument I passed to the method and not with a value that may have been generated while performing the method.
My 2 Cents
Actually, the question of throwing IllegalArgumentException or NullPointerException is in my humble view only a "holy war" for a minority with an incomlete understanding of exception handling in Java. In general, the rules are simple, and as follows:
argument constraint violations must be indicated as fast as possible (-> fast fail), in order to avoid illegal states which are much harder to debug
in case of an invalid null pointer for whatever reason, throw NullPointerException
in case of an illegal array/collection index, throw ArrayIndexOutOfBounds
in case of a negative array/collection size, throw NegativeArraySizeException
in case of an illegal argument that is not covered by the above, and for which you don't have another more specific exception type, throw IllegalArgumentException as a wastebasket
on the other hand, in case of a constraint violation WITHIN A FIELD that could not be avoided by fast fail for some valid reason, catch and rethrow as IllegalStateException or a more specific checked exception. Never let pass the original NullPointerException, ArrayIndexOutOfBounds, etc in this case!
There are at least three very good reasons against the case of mapping all kinds of argument constraint violations to IllegalArgumentException, with the third probably being so severe as to mark the practice bad style:
(1) A programmer cannot a safely assume that all cases of argument constraint violations result in IllegalArgumentException, because the large majority of standard classes use this exception rather as a wastebasket if there is no more specific kind of exception available. Trying to map all cases of argument constraint violations to IllegalArgumentException in your API only leads to programmer frustration using your classes, as the standard libraries mostly follow different rules that violate yours, and most of your API users will use them as well!
(2) Mapping the exceptions actually results in a different kind of anomaly, caused by single inheritance: All Java exceptions are classes, and therefore support single inheritance only. Therefore, there is no way to create an exception that is truly say both a NullPointerException and an IllegalArgumentException, as subclasses can only inherit from one or the other. Throwing an IllegalArgumentException in case of a null argument therefore makes it harder for API users to distinguish between problems whenever a program tries to programmatically correct the problem, for example by feeding default values into a call repeat!
(3) Mapping actually creates the danger of bug masking: In order to map argument constraint violations into IllegalArgumentException, you'll need to code an outer try-catch within every method that has any constrained arguments. However, simply catching RuntimeException in this catch block is out of the question, because that risks mapping documented RuntimeExceptions thrown by libery methods used within yours into IllegalArgumentException, even if they are no caused by argument constraint violations. So you need to be very specific, but even that effort doesn't protect you from the case that you accidentally map an undocumented runtime exception of another API (i.e. a bug) into an IllegalArgumentException of your API. Even the most careful mapping therefore risks masking programming errors of other library makers as argument constraint violations of your method's users, which is simply hillareous behavior!
With the standard practice on the other hand, the rules stay simple, and exception causes stay unmasked and specific. For the method caller, the rules are easy as well:
- if you encounter a documented runtime exception of any kind because you passed an illegal value, either repeat the call with a default (for this specific exceptions are neccessary), or correct your code
- if on the other hand you enccounter a runtime exception that is not documented to happen for a given set of arguments, file a bug report to the method's makers to ensure that either their code or their documentation is fixed.
The accepted practice if to use the IllegalArgumentException( String message ) to declare a parameter to be invalid and give as much detail as possible... So to say that a parameters was found to be null while exception non-null, you would do something like this:
if( variable == null )
throw new IllegalArgumentException("The object 'variable' cannot be null");
You have virtually no reason to implicitly use the "NullPointerException". The NullPointerException is an exception thrown by the Java Virtual Machine when you try to execute code on null reference (Like toString()).
Throwing an exception that's exclusive to null arguments (whether NullPointerException or a custom type) makes automated null testing more reliable. This automated testing can be done with reflection and a set of default values, as in Guava's NullPointerTester. For example, NullPointerTester would attempt to call the following method...
Foo(String string, List<?> list) {
checkArgument(string.length() > 0);
// missing null check for list!
this.string = string;
this.list = list;
}
...with two lists of arguments: "", null and null, ImmutableList.of(). It would test that each of these calls throws the expected NullPointerException. For this implementation, passing a null list does not produce NullPointerException. It does, however, happen to produce an IllegalArgumentException because NullPointerTester happens to use a default string of "". If NullPointerTester expects only NullPointerException for null values, it catches the bug. If it expects IllegalArgumentException, it misses it.
In general, a developer should never throw a NullPointerException. This exception is thrown by the runtime when code attempts to dereference a variable who's value is null. Therefore, if your method wants to explicitly disallow null, as opposed to just happening to have a null value raise a NullPointerException, you should throw an IllegalArgumentException.
Some collections assume that null is rejected using NullPointerException rather than IllegalArgumentException. For example, if you compare a set containing null to a set that rejects null, the first set will call containsAll on the other and catch its NullPointerException -- but not IllegalArgumentException. (I'm looking at the implementation of AbstractSet.equals.)
You could reasonably argue that using unchecked exceptions in this way is an antipattern, that comparing collections that contain null to collections that can't contain null is a likely bug that really should produce an exception, or that putting null in a collection at all is a bad idea. Nevertheless, unless you're willing to say that equals should throw an exception in such a case, you're stuck remembering that NullPointerException is required in certain circumstances but not in others. ("IAE before NPE except after 'c'...")
Somewhat similarly, build tools may insert null checks automatically. Notably, Kotlin's compiler does this when passing a possibly null value to a Java API. And when a check fails, the result is a NullPointerException. So, to give consistent behavior to any Kotlin users and Java users that you have, you'd need to use NullPointerException.
I wanted to single out Null arguments from other illegal arguments, so I derived an exception from IAE named NullArgumentException. Without even needing to read the exception message, I know that a null argument was passed into a method and by reading the message, I find out which argument was null. I still catch the NullArgumentException with an IAE handler, but in my logs is where I can see the difference quickly.
the dichotomy... Are they non-overlapping? Only non-overlapping parts of a whole can make a dichotomy. As i see it:
throw new IllegalArgumentException(new NullPointerException(NULL_ARGUMENT_IN_METHOD_BAD_BOY_BAD));
According to your scenario, IllegalArgumentException is the best pick, because null is not a valid value for your property.
NullPointerException thrown when attempting to access an object with a reference variable whose current value is null.
IllegalArgumentException thrown when a method receives an argument formatted differently than the method expects.
The definitions from the links to the two exceptions above are
IllegalArgumentException: Thrown to indicate that a method has been passed an illegal or inappropriate argument.
NullPointerException: Thrown when an application attempts to use null in a case where an object is required.
The big difference here is the IllegalArgumentException is supposed to be used when checking that an argument to a method is valid. NullPointerException is supposed to be used whenever an object being "used" when it is null.
I hope that helps put the two in perspective.
If it's a "setter", or somewhere I'm getting a member to use later, I tend to use IllegalArgumentException.
If it's something I'm going to use (dereference) right now in the method, I throw a NullPointerException proactively. I like this better than letting the runtime do it, because I can provide a helpful message (seems like the runtime could do this too, but that's a rant for another day).
If I'm overriding a method, I use whatever the overridden method uses.
You should throw an IllegalArgumentException, as it will make it obvious to the programmer that he has done something invalid. Developers are so used to seeing NPE thrown by the VM, that any programmer would not immediately realize his error, and would start looking around randomly, or worse, blame your code for being 'buggy'.
In this case, IllegalArgumentException conveys clear information to the user using your API that the " should not be null". As other forum users pointed out you could use NPE if you want to as long as you convey the right information to the user using your API.
GaryF and tweakt dropped "Effective Java" (which I swear by) references which recommends using NPE. And looking at how other good APIs are constructed is the best way to see how to construct your API.
Another good example is to look at the Spring APIs. For example, org.springframework.beans.BeanUtils.instantiateClass(Constructor ctor, Object[] args) has a Assert.notNull(ctor, "Constructor must not be null") line. org.springframework.util.Assert.notNull(Object object, String message) method checks to see if the argument (object) passed in is null and if it is it throws a new IllegalArgumentException(message) which is then caught in the org.springframework.beans.BeanUtils.instantiateClass(...) method.
Ideally runtime exceptions should not be thrown. A checked exception(business exception) should be created for your scenario. Because if either of these exception is thrown and logged, it misguides the developer while going through the logs. Instead business exceptions do not create that panic and usually ignored while troubleshooting logs.
If you choose to throw a NPE and you are using the argument in your method, it might be redundant and expensive to explicitly check for a null. I think the VM already does that for you.

Should I throw an Exception if logger is Null? [duplicate]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 6 years ago.
Improve this question
I have a simple setter method for a property and null is not appropriate for this particular property. I have always been torn in this situation: should I throw an IllegalArgumentException, or a NullPointerException? From the javadocs, both seem appropriate. Is there some kind of an understood standard? Or is this just one of those things that you should do whatever you prefer and both are really correct?
You should be using IllegalArgumentException (IAE), not NullPointerException (NPE) for the following reasons:
First, the NPE JavaDoc explicitly lists the cases where NPE is appropriate. Notice that all of them are thrown by the runtime when null is used inappropriately. In contrast, the IAE JavaDoc couldn't be more clear: "Thrown to indicate that a method has been passed an illegal or inappropriate argument." Yup, that's you!
Second, when you see an NPE in a stack trace, what do you assume? Probably that someone dereferenced a null. When you see IAE, you assume the caller of the method at the top of the stack passed in an illegal value. Again, the latter assumption is true, the former is misleading.
Third, since IAE is clearly designed for validating parameters, you have to assume it as the default choice of exception, so why would you choose NPE instead? Certainly not for different behavior -- do you really expect calling code to catch NPE's separately from IAE and do something different as a result? Are you trying to communicate a more specific error message? But you can do that in the exception message text anyway, as you should for all other incorrect parameters.
Fourth, all other incorrect parameter data will be IAE, so why not be consistent? Why is it that an illegal null is so special that it deserves a separate exception from all other types of illegal arguments?
Finally, I accept the argument given by other answers that parts of the Java API use NPE in this manner. However, the Java API is inconsistent with everything from exception types to naming conventions, so I think just blindly copying (your favorite part of) the Java API isn't a good enough argument to trump these other considerations.
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.
The standard is to throw the NullPointerException. The generally infallible "Effective Java" discusses this briefly in Item 42 (first edition), Item 60 (second edition), or Item 72 (third edition) "Favor the use of standard exceptions":
"Arguably, all erroneous method
invocations boil down to an illegal
argument or illegal state, but other
exceptions are standardly used for
certain kinds of illegal arguments and
states. If a caller passes null in
some parameter for which null values
are prohibited, convention dictates
that NullPointerException be thrown
rather than IllegalArgumentException."
I was all in favour of throwing IllegalArgumentException for null parameters, until today, when I noticed the java.util.Objects.requireNonNull method in Java 7. With that method, instead of doing:
if (param == null) {
throw new IllegalArgumentException("param cannot be null.");
}
you can do:
Objects.requireNonNull(param);
and it will throw a NullPointerException if the parameter you pass it is null.
Given that that method is right bang in the middle of java.util I take its existence to be a pretty strong indication that throwing NullPointerException is "the Java way of doing things".
I think I'm decided at any rate.
Note that the arguments about hard debugging are bogus because you can of course provide a message to NullPointerException saying what was null and why it shouldn't be null. Just like with IllegalArgumentException.
One added advantage of NullPointerException is that, in highly performance critical code, you could dispense with an explicit check for null (and a NullPointerException with a friendly error message), and just rely on the NullPointerException you'll get automatically when you call a method on the null parameter. Provided you call a method quickly (i.e. fail fast), then you have essentially the same effect, just not quite as user friendly for the developer. Most times it's probably better to check explicitly and throw with a useful message to indicate which parameter was null, but it's nice to have the option of changing that if performance dictates without breaking the published contract of the method/constructor.
I tend to follow the design of JDK libraries, especially Collections and Concurrency (Joshua Bloch, Doug Lea, those guys know how to design solid APIs). Anyway, many APIs in the JDK pro-actively throws NullPointerException.
For example, the Javadoc for Map.containsKey states:
#throws NullPointerException if the key is null and this map
does not permit null keys (optional).
It's perfectly valid to throw your own NPE. The convention is to include the parameter name which was null in the message of the exception.
The pattern goes:
public void someMethod(Object mustNotBeNull) {
if (mustNotBeNull == null) {
throw new NullPointerException("mustNotBeNull must not be null");
}
}
Whatever you do, don't allow a bad value to get set and throw an exception later when other code attempts to use it. That makes debugging a nightmare. You should always the follow the "fail-fast" principle.
Voted up Jason Cohen's argument because it was well presented. Let me dismember it step by step. ;-)
The NPE JavaDoc explicitly says, "other illegal uses of the null object". If it was just limited to situations where the runtime encounters a null when it shouldn't, all such cases could be defined far more succinctly.
Can't help it if you assume the wrong thing, but assuming encapsulation is applied properly, you really shouldn't care or notice whether a null was dereferenced inappropriately vs. whether a method detected an inappropriate null and fired an exception off.
I'd choose NPE over IAE for multiple reasons
It is more specific about the nature of the illegal operation
Logic that mistakenly allows nulls tends to be very different from logic that mistakenly allows illegal values. For example, if I'm validating data entered by a user, if I get value that is unacceptable, the source of that error is with the end user of the application. If I get a null, that's programmer error.
Invalid values can cause things like stack overflows, out of memory errors, parsing exceptions, etc. Indeed, most errors generally present, at some point, as an invalid value in some method call. For this reason I see IAE as actually the MOST GENERAL of all exceptions under RuntimeException.
Actually, other invalid arguments can result in all kinds of other exceptions. UnknownHostException, FileNotFoundException, a variety of syntax error exceptions, IndexOutOfBoundsException, authentication failures, etc., etc.
In general, I feel NPE is much maligned because traditionally has been associated with code that fails to follow the fail fast principle. That, plus the JDK's failure to populate NPE's with a message string really has created a strong negative sentiment that isn't well founded. Indeed, the difference between NPE and IAE from a runtime perspective is strictly the name. From that perspective, the more precise you are with the name, the more clarity you give to the caller.
It's a "Holy War" style question. In others words, both alternatives are good, but people will have their preferences which they will defend to the death.
If it's a setter method and null is being passed to it, I think it would make more sense to throw an IllegalArgumentException. A NullPointerException seems to make more sense in the case where you're attempting to actually use the null.
So, if you're using it and it's null, NullPointer. If it's being passed in and it's null, IllegalArgument.
Apache Commons Lang has a NullArgumentException that does a number of the things discussed here: it extends IllegalArgumentException and its sole constructor takes the name of the argument which should have been non-null.
While I feel that throwing something like a NullArgumentException or IllegalArgumentException more accurately describes the exceptional circumstances, my colleagues and I have chosen to defer to Bloch's advice on the subject.
As a subjective question this should be closed, but as it's still open:
This is part of the internal policy used at my previous place of employment and it worked really well. This is all from memory so I can't remember the exact wording. It's worth noting that they did not use checked exceptions, but that is beyond the scope of the question. The unchecked exceptions they did use fell into 3 main categories.
NullPointerException: Do not throw intentionally. NPEs are to be thrown only by the VM when dereferencing a null reference. All possible effort is to be made to ensure that these are never thrown. #Nullable and #NotNull should be used in conjunction with code analysis tools to find these errors.
IllegalArgumentException: Thrown when an argument to a function does not conform to the public documentation, such that the error can be identified and described in terms of the arguments passed in. The OP's situation would fall into this category.
IllegalStateException: Thrown when a function is called and its arguments are either unexpected at the time they are passed or incompatible with the state of the object the method is a member of.
For example, there were two internal versions of the IndexOutOfBoundsException used in things that had a length. One a sub-class of IllegalStateException, used if the index was larger than the length. The other a subclass of IllegalArgumentException, used if the index was negative. This was because you could add more items to the object and the argument would be valid, while a negative number is never valid.
As I said, this system works really well, and it took someone to explain why the distinction is there: "Depending on the type of error it is quite straightforward for you to figure out what to do. Even if you can't actually figure out what went wrong you can figure out where to catch that error and create additional debugging information."
NullPointerException: Handle the Null case or put in an assertion so that the NPE is not thrown. If you put in an assertion is just one of the other two types. If possible, continue debugging as if the assertion was there in the first place.
IllegalArgumentException: you have something wrong at your call site. If the values being passed in are from another function, find out why you are receiving an incorrect value. If you are passing in one of your arguments propagate the error checks up the call stack until you find the function that is not returning what you expect.
IllegalStateException: You have not called your functions in the correct order. If you are using one of your arguments, check them and throw an IllegalArgumentException describing the issue. You can then propagate the cheeks up against the stack until you find the issue.
Anyway, his point was that you can only copy the IllegalArgumentAssertions up the stack. There is no way for you to propagate the IllegalStateExceptions or NullPointerExceptions up the stack because they had something to do with your function.
Couldn't agree more with what's being said. Fail early, fail fast. Pretty good Exception mantra.
The question about which Exception to throw is mostly a matter of personal taste. In my mind IllegalArgumentException seems more specific than using a NPE since it's telling me that the problem was with an argument I passed to the method and not with a value that may have been generated while performing the method.
My 2 Cents
Actually, the question of throwing IllegalArgumentException or NullPointerException is in my humble view only a "holy war" for a minority with an incomlete understanding of exception handling in Java. In general, the rules are simple, and as follows:
argument constraint violations must be indicated as fast as possible (-> fast fail), in order to avoid illegal states which are much harder to debug
in case of an invalid null pointer for whatever reason, throw NullPointerException
in case of an illegal array/collection index, throw ArrayIndexOutOfBounds
in case of a negative array/collection size, throw NegativeArraySizeException
in case of an illegal argument that is not covered by the above, and for which you don't have another more specific exception type, throw IllegalArgumentException as a wastebasket
on the other hand, in case of a constraint violation WITHIN A FIELD that could not be avoided by fast fail for some valid reason, catch and rethrow as IllegalStateException or a more specific checked exception. Never let pass the original NullPointerException, ArrayIndexOutOfBounds, etc in this case!
There are at least three very good reasons against the case of mapping all kinds of argument constraint violations to IllegalArgumentException, with the third probably being so severe as to mark the practice bad style:
(1) A programmer cannot a safely assume that all cases of argument constraint violations result in IllegalArgumentException, because the large majority of standard classes use this exception rather as a wastebasket if there is no more specific kind of exception available. Trying to map all cases of argument constraint violations to IllegalArgumentException in your API only leads to programmer frustration using your classes, as the standard libraries mostly follow different rules that violate yours, and most of your API users will use them as well!
(2) Mapping the exceptions actually results in a different kind of anomaly, caused by single inheritance: All Java exceptions are classes, and therefore support single inheritance only. Therefore, there is no way to create an exception that is truly say both a NullPointerException and an IllegalArgumentException, as subclasses can only inherit from one or the other. Throwing an IllegalArgumentException in case of a null argument therefore makes it harder for API users to distinguish between problems whenever a program tries to programmatically correct the problem, for example by feeding default values into a call repeat!
(3) Mapping actually creates the danger of bug masking: In order to map argument constraint violations into IllegalArgumentException, you'll need to code an outer try-catch within every method that has any constrained arguments. However, simply catching RuntimeException in this catch block is out of the question, because that risks mapping documented RuntimeExceptions thrown by libery methods used within yours into IllegalArgumentException, even if they are no caused by argument constraint violations. So you need to be very specific, but even that effort doesn't protect you from the case that you accidentally map an undocumented runtime exception of another API (i.e. a bug) into an IllegalArgumentException of your API. Even the most careful mapping therefore risks masking programming errors of other library makers as argument constraint violations of your method's users, which is simply hillareous behavior!
With the standard practice on the other hand, the rules stay simple, and exception causes stay unmasked and specific. For the method caller, the rules are easy as well:
- if you encounter a documented runtime exception of any kind because you passed an illegal value, either repeat the call with a default (for this specific exceptions are neccessary), or correct your code
- if on the other hand you enccounter a runtime exception that is not documented to happen for a given set of arguments, file a bug report to the method's makers to ensure that either their code or their documentation is fixed.
The accepted practice if to use the IllegalArgumentException( String message ) to declare a parameter to be invalid and give as much detail as possible... So to say that a parameters was found to be null while exception non-null, you would do something like this:
if( variable == null )
throw new IllegalArgumentException("The object 'variable' cannot be null");
You have virtually no reason to implicitly use the "NullPointerException". The NullPointerException is an exception thrown by the Java Virtual Machine when you try to execute code on null reference (Like toString()).
Throwing an exception that's exclusive to null arguments (whether NullPointerException or a custom type) makes automated null testing more reliable. This automated testing can be done with reflection and a set of default values, as in Guava's NullPointerTester. For example, NullPointerTester would attempt to call the following method...
Foo(String string, List<?> list) {
checkArgument(string.length() > 0);
// missing null check for list!
this.string = string;
this.list = list;
}
...with two lists of arguments: "", null and null, ImmutableList.of(). It would test that each of these calls throws the expected NullPointerException. For this implementation, passing a null list does not produce NullPointerException. It does, however, happen to produce an IllegalArgumentException because NullPointerTester happens to use a default string of "". If NullPointerTester expects only NullPointerException for null values, it catches the bug. If it expects IllegalArgumentException, it misses it.
In general, a developer should never throw a NullPointerException. This exception is thrown by the runtime when code attempts to dereference a variable who's value is null. Therefore, if your method wants to explicitly disallow null, as opposed to just happening to have a null value raise a NullPointerException, you should throw an IllegalArgumentException.
Some collections assume that null is rejected using NullPointerException rather than IllegalArgumentException. For example, if you compare a set containing null to a set that rejects null, the first set will call containsAll on the other and catch its NullPointerException -- but not IllegalArgumentException. (I'm looking at the implementation of AbstractSet.equals.)
You could reasonably argue that using unchecked exceptions in this way is an antipattern, that comparing collections that contain null to collections that can't contain null is a likely bug that really should produce an exception, or that putting null in a collection at all is a bad idea. Nevertheless, unless you're willing to say that equals should throw an exception in such a case, you're stuck remembering that NullPointerException is required in certain circumstances but not in others. ("IAE before NPE except after 'c'...")
Somewhat similarly, build tools may insert null checks automatically. Notably, Kotlin's compiler does this when passing a possibly null value to a Java API. And when a check fails, the result is a NullPointerException. So, to give consistent behavior to any Kotlin users and Java users that you have, you'd need to use NullPointerException.
I wanted to single out Null arguments from other illegal arguments, so I derived an exception from IAE named NullArgumentException. Without even needing to read the exception message, I know that a null argument was passed into a method and by reading the message, I find out which argument was null. I still catch the NullArgumentException with an IAE handler, but in my logs is where I can see the difference quickly.
the dichotomy... Are they non-overlapping? Only non-overlapping parts of a whole can make a dichotomy. As i see it:
throw new IllegalArgumentException(new NullPointerException(NULL_ARGUMENT_IN_METHOD_BAD_BOY_BAD));
According to your scenario, IllegalArgumentException is the best pick, because null is not a valid value for your property.
NullPointerException thrown when attempting to access an object with a reference variable whose current value is null.
IllegalArgumentException thrown when a method receives an argument formatted differently than the method expects.
The definitions from the links to the two exceptions above are
IllegalArgumentException: Thrown to indicate that a method has been passed an illegal or inappropriate argument.
NullPointerException: Thrown when an application attempts to use null in a case where an object is required.
The big difference here is the IllegalArgumentException is supposed to be used when checking that an argument to a method is valid. NullPointerException is supposed to be used whenever an object being "used" when it is null.
I hope that helps put the two in perspective.
If it's a "setter", or somewhere I'm getting a member to use later, I tend to use IllegalArgumentException.
If it's something I'm going to use (dereference) right now in the method, I throw a NullPointerException proactively. I like this better than letting the runtime do it, because I can provide a helpful message (seems like the runtime could do this too, but that's a rant for another day).
If I'm overriding a method, I use whatever the overridden method uses.
You should throw an IllegalArgumentException, as it will make it obvious to the programmer that he has done something invalid. Developers are so used to seeing NPE thrown by the VM, that any programmer would not immediately realize his error, and would start looking around randomly, or worse, blame your code for being 'buggy'.
In this case, IllegalArgumentException conveys clear information to the user using your API that the " should not be null". As other forum users pointed out you could use NPE if you want to as long as you convey the right information to the user using your API.
GaryF and tweakt dropped "Effective Java" (which I swear by) references which recommends using NPE. And looking at how other good APIs are constructed is the best way to see how to construct your API.
Another good example is to look at the Spring APIs. For example, org.springframework.beans.BeanUtils.instantiateClass(Constructor ctor, Object[] args) has a Assert.notNull(ctor, "Constructor must not be null") line. org.springframework.util.Assert.notNull(Object object, String message) method checks to see if the argument (object) passed in is null and if it is it throws a new IllegalArgumentException(message) which is then caught in the org.springframework.beans.BeanUtils.instantiateClass(...) method.
Ideally runtime exceptions should not be thrown. A checked exception(business exception) should be created for your scenario. Because if either of these exception is thrown and logged, it misguides the developer while going through the logs. Instead business exceptions do not create that panic and usually ignored while troubleshooting logs.
If you choose to throw a NPE and you are using the argument in your method, it might be redundant and expensive to explicitly check for a null. I think the VM already does that for you.

Should I throw a NullPointerException explicitly or let Java do it for me?

As the title says, I am wondering what the best practice is regarding the throwing of NullPointerExceptions. Specifically, if I have an external library function that can return null in circumstances that I don't want to actually handle (see below for a specific example), as the null indicates a problem with the software. The question is, should I
check the return value for null and throw the NullPointerException myself, or
should I just let Java do the dirty work for me as soon as I try to use the object.
The first approach lets me add some additional information, since I get to construct the NullPointerException, but the second makes for cleaner code in my opinion. I would also wonder as to any performance implications, that is, is Java more efficient at throwing the NPE "natively"?
By way of example, I am trying to use the Java Speech API to create a speech synthesizer using the following code:
synthesizer = Central.createSynthesizer(generalDesc);
if (synthesizer == null) {
// (1) throw NPE explicitly
throw new NullPointerException("No general domain synthesizer found.");
}
// (2) let the JVM throw the NPE when dereferencing
synthesizer.allocate();
Central.createSynthesizer returns null if it cannot find a suitable synthesizer, which is most often caused by a missing speech.properties file. So it's a matter of wrong setup of the system, and pretty unrecoverable from at runtime, rather than circumstances that need to be handled programmatically. As such, I believe throwing a NullPointerException is a valid response, since it indicates a bug (not in the code but in the deployment of the software). But since the synthesizer object is dereferenced in the very next statement, should I just let the JVM throw the NPE for me and save the null check?
Addendum: Considering that speech.properties gets loaded when the JVM starts needs to exist on the filesystem in (normally) "user.home" or "java.home/lib", it is puzzling that createSynthesizer doesn't straight up throw an NPE (which is what I had written originally in a Freudian slip) when it fails to find it but returns null instead. I think that throwing a NullPointerException is the right thing to do here, because it indicates an actual bug in the deployment of the software.
In your case: neither. Check for null and throw more meaningful exception, not NPE.
In general - if NPE should not occur, don't test for it explicitly, Java will do it for you. Less tests to write, less code to read, less complexity to analyze.
However if null is expected test it as soon as possible and interpret accordingly. Otherwise NullPointerException will occur somewhere later in different line/method, making it harder to debug the real problem.
I'd say that you should never explicitly create a NullPointerException and instead use an exception type that more clearly describes the situation. In your case, I'd say IllegalStateException would fit the situation "wrong setup of the system, and pretty unrecoverable from at runtime". Or you could create your own ComponentMissingException. In cases where a required method parameter is null, IllegalArgumentException is typically used.
I dont like having null be a valid return value, even in "exceptional circumstances". So I take yet another approach.
In your case I'd annotate the method createSynthesizer(...) with #NotNull (#NotNull is an amazing annotation). Instead of an NPE, I'd get an IllegalStateException as soon as createSynthesizer(...) would want to return null.
You'd get a:
java.lang.IllegalStateException: #NotNull method .../.../createSynthetiser(...) must not return null
There are several benefits to this approach:
both NullPointerException and IllegalStateException extends RuntimeException so you're not fundamentally changing your program
the exception shall be thrown immediately where the error happens (not later on, once you either check/throw yourself or once you try to dereference null)
you don't need to bother writing the if ... == null / throw part anymore.
As a, gigantic, added benefit some IDE (like IntelliJ IDEA) will warn you in real-time about probable #NotNull violations.
Regarding the original code:
synthesizer = Central.createSynthesizer(generalDesc);
if (synthesizer == null) {
// (1) throw NPE explicitly
throw new NullPointerException("No general domain synthesizer found.");
}
// (2) let the JVM throw the NPE when dereferencing
synthesizer.allocate();
My take is that throwing the NPE as shown here is OK, but with tremendous caveats. The caveat under which this is OK is only if the NPE ctor argument is a sufficiently descriptive (and hopefully unique) message (one hopefully pulled out of a constant or resource set.) Another caveat is that your main priority to get things out of the door, and such casea, this would count as an acceptable quick-n-dirty solution.
Under ideal circumstances, my preference is use exceptions specific to invalid configurations. And when those are not available, to either use NPE subclasses (like Apache Commons Math's NullArgumentException) or the old exceptions found in Apache Common Lang 2.x. That is my position for NPEs and IllegalArgument-type exceptions. I don't necessarily agree with Apache Common Lang's position on preferring to use the standard JDK exceptions over more semantically-relevant exceptions. But that's just me, and I'm getting off the tangent...
... so back to the original question. As I said before, throwing the NPE like that is ok in a quick-n-dirty way (when you are in one of those "need to get that sh1t out!!(10+1)" kind of situations.
Notice, however, this is a NPE caused by an application or systems configuration problem, as you correctly identified it. That is, the NPE is not the root cause, by a symptom or effect of another error condition (in this case, a configuration or environment error.)
Central.createSynthesizer returns null if it cannot find a suitable
synthesizer, which is most often caused by a missing speech.properties
file. So it's a matter of wrong setup of the system, and pretty
unrecoverable from at runtime, rather than circumstances that need to
be handled programmatically.
Unrecoverability is not a certainty. An application could have other ways to handle this situation programmatically.
As such, I believe throwing a
NullPointerException is a valid response, since it indicates a bug
(not in the code but in the deployment of the software). But since the
synthesizer object is dereferenced in the very next statement, should
I just let the JVM throw the NPE for me and save the null check?
I wouldn't do that, even under get-that-sh1t-out-of-the-door circumstances. The NPE thrown that way by the JVM will have a very uninformative message in it. In general, check everything for NULL and throw a descriptive exception (NPE or otherwise) when you encounter one.
Don't check for NPEs if you can guarantee that whatever you are getting (parameters for example) has already been checked for NPEs already (in a design-by-contract kind of way.)
Addendum: Considering that speech.properties gets loaded when the JVM
starts needs to exist on the filesystem in (normally) "user.home" or
"java.home/lib", it is puzzling that createSynthesizer doesn't
straight up throw an NPE (which is what I had written originally in a
Freudian slip) when it fails to find it but returns null instead.
Again, that's because the response to that situation is application specific. The application might decide to go on a limping mode with partial functionality instead of crashing and burning to the ground. If createSynthesizer were to throw a NPE, then the API designer forces the application designer to adopt the later behavior, or go to somewhat greater lengths to implement a "limping" mode of operations (by having to use a catch/try instead of a simple if-null test.
I think that throwing a NullPointerException is the right thing to do
here, because it indicates an actual bug in the deployment of the
software.
Again, only if the NPE is a quick-n-dirty solution to get things out of the door. Under those conditions, it is ok. A better approach is to identify what this is, a configuration error.
So it would be better to have application specific exceptions like IllegalConfigurationException or InvalidConfigurationException or IncompleteConfigurationException. I don't like using java.lang.IllegalStateException for such cases, because this is not caused by calling something in an invalid state. The invalid state got reached because of an invalid configuration. Maybe I'm playing semantic games, but there is something icky about using IllegalStateException in such cases (that's just me being subjective, I know.)
Very interesting question.
I think some kind of ProblemCreatingSynthesizerException should be thrown by that method, instead of returning null.
I'd put the null check and throw a NPE or other custom ProblemWithSynthesizerException of your own (Sun, for some reason, conceived this Exception as a JVM-ish exception, not meant to be used by the programmer. This is what it says in some certification tutorials and books. However, I don't buy that, and some often I throw my own NPEs in my libraries).
I have never used Java, but if I were using the application, I would want to see an error message than a crash. NullPointerException sounds like a bug in the code to me - I would rather see an error message with directions on how to properly configure the program, or at least a hyperlink to a web page that had such directions.
If I were a user and saw that a program had terminated with NullPointerException, I would file a bug against the program, or at least be confused as to what to do next.

Where to catch and process null arguments?

When I code, I often ask myself the same question :
Do I have to verify all arguments are not null ? So, in each method, I will have something like that :
if (arg1 == null)
{
throw FooException("...");
}
if (arg2 == null)
{
throw FooException("...");
}
If not, in which case is preferable ?
What's the best practices ?
As always, it depends.
If you're writing an API to be used by other teams / organizations, such defensive programming with precondition checks on public functions can really help your users; when using an external library, a meaningful error message like 'argument passed to foo() should not be null' is way better than NullPointerException thrown from some inner class.
Outside of API, though, I think such checks clutter the code too much. Thrown NullPointerExceptions are usually pretty easy to trace with debugger anyway. In languages that support them, you can consider using assertions - their syntax is usually less cumbersome, and you can turn them off on production so the checks won't degrade performance.
Unfortunetly, yes. you should check all arguments. Now ideally, if you code with good design practices one function should not have more than 4 or 5 arguments, at the most.
Having said that, one should always check for null values in function entry and throw appropriate exception or IllegalArgumentException (my fav).
Furhter, one should never pass NULL to a function and should never return a NULL. Sounds simple but it will save lots of code and bugs. Have a look at the NULL Design Pattern too.
Depends, if you want different exceptions i guess you would have to do that for all occasions where you might get a null value. Another way would be to user DATATYP.TryParse(). Look that up.
Hope it helps.
Since you're throwing an exception anyway, not verifying them would probably just lead to a nullpointerexception or something similar. I'm not entirely sure what the best practices are myself.
You should ideally always verify any arguments before you perform any action that might modify any state or data associated with said arguments. It's better to fail early and in a manageable way (by throwing a exception) than to end up with an inconsistent state / data which then also has to be resolved.
Your methods are expecting certain data to be there, there are some cases when it should be safe to assume that it is actually there (say inside a private method, which is called from other methods which validate input). However in general I would recommend validating arguments whenever they are:
Supplied by a user.
Supplied as part of an API.
Passed between modules of a system .
It's might be worth taking a look at this previous StackOverflow question.
I feel it's mostly down to common sense, and a little down to personal preference.
As others have mentioned, if it's a public API then you want to provide clear error messages wherever possible, so it's best to check parameters before they are used and throw exceptions with messages as per your example.
If it's internal code then there are two other options to think about: use assertions, or don't bother with the validation and rely on debugging. As a rule of thumb, I'll put assertions in if it's code that I expect other developers will be calling or if the condition is subtle enough that debugging it might be a pain. Otherwise, I'll just allow it to fail.
Sometimes you can avoid the issue by using the Null Object pattern. If it's a public API I'd still be inclined to include the checks though.

IllegalArgumentException or NullPointerException for a null parameter? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 6 years ago.
Improve this question
I have a simple setter method for a property and null is not appropriate for this particular property. I have always been torn in this situation: should I throw an IllegalArgumentException, or a NullPointerException? From the javadocs, both seem appropriate. Is there some kind of an understood standard? Or is this just one of those things that you should do whatever you prefer and both are really correct?
You should be using IllegalArgumentException (IAE), not NullPointerException (NPE) for the following reasons:
First, the NPE JavaDoc explicitly lists the cases where NPE is appropriate. Notice that all of them are thrown by the runtime when null is used inappropriately. In contrast, the IAE JavaDoc couldn't be more clear: "Thrown to indicate that a method has been passed an illegal or inappropriate argument." Yup, that's you!
Second, when you see an NPE in a stack trace, what do you assume? Probably that someone dereferenced a null. When you see IAE, you assume the caller of the method at the top of the stack passed in an illegal value. Again, the latter assumption is true, the former is misleading.
Third, since IAE is clearly designed for validating parameters, you have to assume it as the default choice of exception, so why would you choose NPE instead? Certainly not for different behavior -- do you really expect calling code to catch NPE's separately from IAE and do something different as a result? Are you trying to communicate a more specific error message? But you can do that in the exception message text anyway, as you should for all other incorrect parameters.
Fourth, all other incorrect parameter data will be IAE, so why not be consistent? Why is it that an illegal null is so special that it deserves a separate exception from all other types of illegal arguments?
Finally, I accept the argument given by other answers that parts of the Java API use NPE in this manner. However, the Java API is inconsistent with everything from exception types to naming conventions, so I think just blindly copying (your favorite part of) the Java API isn't a good enough argument to trump these other considerations.
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.
The standard is to throw the NullPointerException. The generally infallible "Effective Java" discusses this briefly in Item 42 (first edition), Item 60 (second edition), or Item 72 (third edition) "Favor the use of standard exceptions":
"Arguably, all erroneous method
invocations boil down to an illegal
argument or illegal state, but other
exceptions are standardly used for
certain kinds of illegal arguments and
states. If a caller passes null in
some parameter for which null values
are prohibited, convention dictates
that NullPointerException be thrown
rather than IllegalArgumentException."
I was all in favour of throwing IllegalArgumentException for null parameters, until today, when I noticed the java.util.Objects.requireNonNull method in Java 7. With that method, instead of doing:
if (param == null) {
throw new IllegalArgumentException("param cannot be null.");
}
you can do:
Objects.requireNonNull(param);
and it will throw a NullPointerException if the parameter you pass it is null.
Given that that method is right bang in the middle of java.util I take its existence to be a pretty strong indication that throwing NullPointerException is "the Java way of doing things".
I think I'm decided at any rate.
Note that the arguments about hard debugging are bogus because you can of course provide a message to NullPointerException saying what was null and why it shouldn't be null. Just like with IllegalArgumentException.
One added advantage of NullPointerException is that, in highly performance critical code, you could dispense with an explicit check for null (and a NullPointerException with a friendly error message), and just rely on the NullPointerException you'll get automatically when you call a method on the null parameter. Provided you call a method quickly (i.e. fail fast), then you have essentially the same effect, just not quite as user friendly for the developer. Most times it's probably better to check explicitly and throw with a useful message to indicate which parameter was null, but it's nice to have the option of changing that if performance dictates without breaking the published contract of the method/constructor.
I tend to follow the design of JDK libraries, especially Collections and Concurrency (Joshua Bloch, Doug Lea, those guys know how to design solid APIs). Anyway, many APIs in the JDK pro-actively throws NullPointerException.
For example, the Javadoc for Map.containsKey states:
#throws NullPointerException if the key is null and this map
does not permit null keys (optional).
It's perfectly valid to throw your own NPE. The convention is to include the parameter name which was null in the message of the exception.
The pattern goes:
public void someMethod(Object mustNotBeNull) {
if (mustNotBeNull == null) {
throw new NullPointerException("mustNotBeNull must not be null");
}
}
Whatever you do, don't allow a bad value to get set and throw an exception later when other code attempts to use it. That makes debugging a nightmare. You should always the follow the "fail-fast" principle.
Voted up Jason Cohen's argument because it was well presented. Let me dismember it step by step. ;-)
The NPE JavaDoc explicitly says, "other illegal uses of the null object". If it was just limited to situations where the runtime encounters a null when it shouldn't, all such cases could be defined far more succinctly.
Can't help it if you assume the wrong thing, but assuming encapsulation is applied properly, you really shouldn't care or notice whether a null was dereferenced inappropriately vs. whether a method detected an inappropriate null and fired an exception off.
I'd choose NPE over IAE for multiple reasons
It is more specific about the nature of the illegal operation
Logic that mistakenly allows nulls tends to be very different from logic that mistakenly allows illegal values. For example, if I'm validating data entered by a user, if I get value that is unacceptable, the source of that error is with the end user of the application. If I get a null, that's programmer error.
Invalid values can cause things like stack overflows, out of memory errors, parsing exceptions, etc. Indeed, most errors generally present, at some point, as an invalid value in some method call. For this reason I see IAE as actually the MOST GENERAL of all exceptions under RuntimeException.
Actually, other invalid arguments can result in all kinds of other exceptions. UnknownHostException, FileNotFoundException, a variety of syntax error exceptions, IndexOutOfBoundsException, authentication failures, etc., etc.
In general, I feel NPE is much maligned because traditionally has been associated with code that fails to follow the fail fast principle. That, plus the JDK's failure to populate NPE's with a message string really has created a strong negative sentiment that isn't well founded. Indeed, the difference between NPE and IAE from a runtime perspective is strictly the name. From that perspective, the more precise you are with the name, the more clarity you give to the caller.
It's a "Holy War" style question. In others words, both alternatives are good, but people will have their preferences which they will defend to the death.
If it's a setter method and null is being passed to it, I think it would make more sense to throw an IllegalArgumentException. A NullPointerException seems to make more sense in the case where you're attempting to actually use the null.
So, if you're using it and it's null, NullPointer. If it's being passed in and it's null, IllegalArgument.
Apache Commons Lang has a NullArgumentException that does a number of the things discussed here: it extends IllegalArgumentException and its sole constructor takes the name of the argument which should have been non-null.
While I feel that throwing something like a NullArgumentException or IllegalArgumentException more accurately describes the exceptional circumstances, my colleagues and I have chosen to defer to Bloch's advice on the subject.
As a subjective question this should be closed, but as it's still open:
This is part of the internal policy used at my previous place of employment and it worked really well. This is all from memory so I can't remember the exact wording. It's worth noting that they did not use checked exceptions, but that is beyond the scope of the question. The unchecked exceptions they did use fell into 3 main categories.
NullPointerException: Do not throw intentionally. NPEs are to be thrown only by the VM when dereferencing a null reference. All possible effort is to be made to ensure that these are never thrown. #Nullable and #NotNull should be used in conjunction with code analysis tools to find these errors.
IllegalArgumentException: Thrown when an argument to a function does not conform to the public documentation, such that the error can be identified and described in terms of the arguments passed in. The OP's situation would fall into this category.
IllegalStateException: Thrown when a function is called and its arguments are either unexpected at the time they are passed or incompatible with the state of the object the method is a member of.
For example, there were two internal versions of the IndexOutOfBoundsException used in things that had a length. One a sub-class of IllegalStateException, used if the index was larger than the length. The other a subclass of IllegalArgumentException, used if the index was negative. This was because you could add more items to the object and the argument would be valid, while a negative number is never valid.
As I said, this system works really well, and it took someone to explain why the distinction is there: "Depending on the type of error it is quite straightforward for you to figure out what to do. Even if you can't actually figure out what went wrong you can figure out where to catch that error and create additional debugging information."
NullPointerException: Handle the Null case or put in an assertion so that the NPE is not thrown. If you put in an assertion is just one of the other two types. If possible, continue debugging as if the assertion was there in the first place.
IllegalArgumentException: you have something wrong at your call site. If the values being passed in are from another function, find out why you are receiving an incorrect value. If you are passing in one of your arguments propagate the error checks up the call stack until you find the function that is not returning what you expect.
IllegalStateException: You have not called your functions in the correct order. If you are using one of your arguments, check them and throw an IllegalArgumentException describing the issue. You can then propagate the cheeks up against the stack until you find the issue.
Anyway, his point was that you can only copy the IllegalArgumentAssertions up the stack. There is no way for you to propagate the IllegalStateExceptions or NullPointerExceptions up the stack because they had something to do with your function.
Couldn't agree more with what's being said. Fail early, fail fast. Pretty good Exception mantra.
The question about which Exception to throw is mostly a matter of personal taste. In my mind IllegalArgumentException seems more specific than using a NPE since it's telling me that the problem was with an argument I passed to the method and not with a value that may have been generated while performing the method.
My 2 Cents
Actually, the question of throwing IllegalArgumentException or NullPointerException is in my humble view only a "holy war" for a minority with an incomlete understanding of exception handling in Java. In general, the rules are simple, and as follows:
argument constraint violations must be indicated as fast as possible (-> fast fail), in order to avoid illegal states which are much harder to debug
in case of an invalid null pointer for whatever reason, throw NullPointerException
in case of an illegal array/collection index, throw ArrayIndexOutOfBounds
in case of a negative array/collection size, throw NegativeArraySizeException
in case of an illegal argument that is not covered by the above, and for which you don't have another more specific exception type, throw IllegalArgumentException as a wastebasket
on the other hand, in case of a constraint violation WITHIN A FIELD that could not be avoided by fast fail for some valid reason, catch and rethrow as IllegalStateException or a more specific checked exception. Never let pass the original NullPointerException, ArrayIndexOutOfBounds, etc in this case!
There are at least three very good reasons against the case of mapping all kinds of argument constraint violations to IllegalArgumentException, with the third probably being so severe as to mark the practice bad style:
(1) A programmer cannot a safely assume that all cases of argument constraint violations result in IllegalArgumentException, because the large majority of standard classes use this exception rather as a wastebasket if there is no more specific kind of exception available. Trying to map all cases of argument constraint violations to IllegalArgumentException in your API only leads to programmer frustration using your classes, as the standard libraries mostly follow different rules that violate yours, and most of your API users will use them as well!
(2) Mapping the exceptions actually results in a different kind of anomaly, caused by single inheritance: All Java exceptions are classes, and therefore support single inheritance only. Therefore, there is no way to create an exception that is truly say both a NullPointerException and an IllegalArgumentException, as subclasses can only inherit from one or the other. Throwing an IllegalArgumentException in case of a null argument therefore makes it harder for API users to distinguish between problems whenever a program tries to programmatically correct the problem, for example by feeding default values into a call repeat!
(3) Mapping actually creates the danger of bug masking: In order to map argument constraint violations into IllegalArgumentException, you'll need to code an outer try-catch within every method that has any constrained arguments. However, simply catching RuntimeException in this catch block is out of the question, because that risks mapping documented RuntimeExceptions thrown by libery methods used within yours into IllegalArgumentException, even if they are no caused by argument constraint violations. So you need to be very specific, but even that effort doesn't protect you from the case that you accidentally map an undocumented runtime exception of another API (i.e. a bug) into an IllegalArgumentException of your API. Even the most careful mapping therefore risks masking programming errors of other library makers as argument constraint violations of your method's users, which is simply hillareous behavior!
With the standard practice on the other hand, the rules stay simple, and exception causes stay unmasked and specific. For the method caller, the rules are easy as well:
- if you encounter a documented runtime exception of any kind because you passed an illegal value, either repeat the call with a default (for this specific exceptions are neccessary), or correct your code
- if on the other hand you enccounter a runtime exception that is not documented to happen for a given set of arguments, file a bug report to the method's makers to ensure that either their code or their documentation is fixed.
The accepted practice if to use the IllegalArgumentException( String message ) to declare a parameter to be invalid and give as much detail as possible... So to say that a parameters was found to be null while exception non-null, you would do something like this:
if( variable == null )
throw new IllegalArgumentException("The object 'variable' cannot be null");
You have virtually no reason to implicitly use the "NullPointerException". The NullPointerException is an exception thrown by the Java Virtual Machine when you try to execute code on null reference (Like toString()).
Throwing an exception that's exclusive to null arguments (whether NullPointerException or a custom type) makes automated null testing more reliable. This automated testing can be done with reflection and a set of default values, as in Guava's NullPointerTester. For example, NullPointerTester would attempt to call the following method...
Foo(String string, List<?> list) {
checkArgument(string.length() > 0);
// missing null check for list!
this.string = string;
this.list = list;
}
...with two lists of arguments: "", null and null, ImmutableList.of(). It would test that each of these calls throws the expected NullPointerException. For this implementation, passing a null list does not produce NullPointerException. It does, however, happen to produce an IllegalArgumentException because NullPointerTester happens to use a default string of "". If NullPointerTester expects only NullPointerException for null values, it catches the bug. If it expects IllegalArgumentException, it misses it.
In general, a developer should never throw a NullPointerException. This exception is thrown by the runtime when code attempts to dereference a variable who's value is null. Therefore, if your method wants to explicitly disallow null, as opposed to just happening to have a null value raise a NullPointerException, you should throw an IllegalArgumentException.
Some collections assume that null is rejected using NullPointerException rather than IllegalArgumentException. For example, if you compare a set containing null to a set that rejects null, the first set will call containsAll on the other and catch its NullPointerException -- but not IllegalArgumentException. (I'm looking at the implementation of AbstractSet.equals.)
You could reasonably argue that using unchecked exceptions in this way is an antipattern, that comparing collections that contain null to collections that can't contain null is a likely bug that really should produce an exception, or that putting null in a collection at all is a bad idea. Nevertheless, unless you're willing to say that equals should throw an exception in such a case, you're stuck remembering that NullPointerException is required in certain circumstances but not in others. ("IAE before NPE except after 'c'...")
Somewhat similarly, build tools may insert null checks automatically. Notably, Kotlin's compiler does this when passing a possibly null value to a Java API. And when a check fails, the result is a NullPointerException. So, to give consistent behavior to any Kotlin users and Java users that you have, you'd need to use NullPointerException.
I wanted to single out Null arguments from other illegal arguments, so I derived an exception from IAE named NullArgumentException. Without even needing to read the exception message, I know that a null argument was passed into a method and by reading the message, I find out which argument was null. I still catch the NullArgumentException with an IAE handler, but in my logs is where I can see the difference quickly.
the dichotomy... Are they non-overlapping? Only non-overlapping parts of a whole can make a dichotomy. As i see it:
throw new IllegalArgumentException(new NullPointerException(NULL_ARGUMENT_IN_METHOD_BAD_BOY_BAD));
According to your scenario, IllegalArgumentException is the best pick, because null is not a valid value for your property.
NullPointerException thrown when attempting to access an object with a reference variable whose current value is null.
IllegalArgumentException thrown when a method receives an argument formatted differently than the method expects.
The definitions from the links to the two exceptions above are
IllegalArgumentException: Thrown to indicate that a method has been passed an illegal or inappropriate argument.
NullPointerException: Thrown when an application attempts to use null in a case where an object is required.
The big difference here is the IllegalArgumentException is supposed to be used when checking that an argument to a method is valid. NullPointerException is supposed to be used whenever an object being "used" when it is null.
I hope that helps put the two in perspective.
If it's a "setter", or somewhere I'm getting a member to use later, I tend to use IllegalArgumentException.
If it's something I'm going to use (dereference) right now in the method, I throw a NullPointerException proactively. I like this better than letting the runtime do it, because I can provide a helpful message (seems like the runtime could do this too, but that's a rant for another day).
If I'm overriding a method, I use whatever the overridden method uses.
You should throw an IllegalArgumentException, as it will make it obvious to the programmer that he has done something invalid. Developers are so used to seeing NPE thrown by the VM, that any programmer would not immediately realize his error, and would start looking around randomly, or worse, blame your code for being 'buggy'.
In this case, IllegalArgumentException conveys clear information to the user using your API that the " should not be null". As other forum users pointed out you could use NPE if you want to as long as you convey the right information to the user using your API.
GaryF and tweakt dropped "Effective Java" (which I swear by) references which recommends using NPE. And looking at how other good APIs are constructed is the best way to see how to construct your API.
Another good example is to look at the Spring APIs. For example, org.springframework.beans.BeanUtils.instantiateClass(Constructor ctor, Object[] args) has a Assert.notNull(ctor, "Constructor must not be null") line. org.springframework.util.Assert.notNull(Object object, String message) method checks to see if the argument (object) passed in is null and if it is it throws a new IllegalArgumentException(message) which is then caught in the org.springframework.beans.BeanUtils.instantiateClass(...) method.
Ideally runtime exceptions should not be thrown. A checked exception(business exception) should be created for your scenario. Because if either of these exception is thrown and logged, it misguides the developer while going through the logs. Instead business exceptions do not create that panic and usually ignored while troubleshooting logs.
If you choose to throw a NPE and you are using the argument in your method, it might be redundant and expensive to explicitly check for a null. I think the VM already does that for you.

Categories