Is it okay to throw NullPointerException programmatically?

JavaException HandlingNullpointerexceptionThrow

Java Problem Overview

When there is a post-condition, that return value of a method must not be null, what can be done?

I could do

assert returnValue != null : "Not acceptable null value";

but assertions could be turned off!

So is it okay to do

           throw new NullPointerException("return value is null at method AAA");


Or is it better to use a user-defined exception (like NullReturnValueException ) for such a condition?

Java Solutions

Solution 1 - Java

I would recommend you never throw NullPointerException by yourself.

The main reason not to do this, as Thorbjørn Ravn Andersen says in a comment below, is that you don't wan't to mix 'real, bad NPEs' with NPEs thrown intentionally.

So, until you're confident that you're able to recognize 'valid' NPE, I'd recommend to use IllegalArgumentException when you want to tell to your API user that null is not a valid argument value. Your method's behavior when illegal null-parameter passed should be documented.

Another (more modern imho) option is to use @NotNull annotation near the argument. Here is an article about using @NotNull annotation.

As I mentioned earlier, there can also be cases, when throwing NPE will not be confusing either to you or to your teammates: NPE cause should be clear and recognizable.

For instance, if you use some library with preconditions module, like Guava, then I find using checkNotNull()-like methods is a preferable way to deal with illegally-passed nulls.

checkNotNull(arg, msg) throws NPE, but from the stacktrace it's quite clear, that it was produced by Preconditions.checkNotNull() and thus it's not an unknown bug but rather expected behavior.

Solution 2 - Java

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.

Solution 3 - Java

Given that NullPointerException is the idiomatic way to communicate an unexpected null value in Java, I would recommend you throw a standard NullPointerException and not a homegrown one. Also keep in mind that the principle of least surprise would suggest that you don't invent your own exception type for a case where a system exception type exists.

Assertions are good for debugging but not good if you have to handle certain conditions so that's not really a good way to handle the error condition.

Solution 4 - Java

The problem with NullPointerException is, that it occures when you forget to check if something is null or give the wrong argument that is null, and shouldn't.

From my experience, Java programmers learn very quickly that this exception is caused by the bug in code, so throwing it manually will be extremally confusing for most of them. IllegalArgumentException is better idea when you pass unacceptable argument (such as null, where something must not be null).

It triggers also another heuristic. NPE = someone made error in code here, IllegalArgumentException = the object given to the method is invalid.

On the other hand, the javadoc tells:

> Applications should throw instances of this class to indicate
> other illegal uses of the null object.

So throwing NPE would be legal, however it's not the common practice, so I would recommend IllegalArgumentException.

Solution 5 - Java

There certainly isn't a universal law against throwing NullPointerException, but it's tough to answer if you actually should in such an abstracted example. What you don't want to do is put people up the chain in the position of trying to catch NullPointerException. Code like this (real example, I swear):

catch (NullPointerException npe) {
  if (npe.getMessage().equals("Null return value from getProdByCode") {
    drawToUser("Unable to find a product for the product type code you entered");

Is a surefire indicator you're doing something wrong. So if the null return value is an indicator of some system state that you're actually able to communicate, use an exception that communicates that state. There aren't many cases I can think of where it makes sense to null check a reference just to chuck a nullpointer. Usually the very next line of code would have chucked the nullpointer (or something more informative) anyway!

Solution 6 - Java<br> "Avoid throwing NullPointerExceptions. These are confusing because most people will assume that the virtual machine threw it. Consider using an IllegalArgumentException instead; this will be clearly seen as a programmer-initiated exception."

Solution 7 - Java

I would consider that usage of NullPointerException ok, if you remember the description. That is what the person investigating has work with (line numbers may shift). Also remember to document that your methods throw null pointer exceptions in special cases.

If you check your method parameters right in the beginning, a throw new IllegalArgumentException("foo==null") is acceptable to me too.

Solution 8 - Java

If you describe a method contract where the return value can not be null, then you had better make sure you don't return null. But this isn't a NullPointerException at all. If the value you have to return is null then clearly the caller has either given you bad arguments (IllegalArgumentException), you are not in a valid state (IllegalStateException), or some other much more meaningful exceptional condition has occurred other than NullPointerException (which usually indicates a programming error).

Solution 9 - Java

A book I have called O'Reilly's Java in A Nutshell which is written by an expert lists this definition for NullPointerException:

> Signals an attempt to access a field or invoke a method of a null object.

Since returning null isn't either of those things, I think it'd be more appropriate to write your own exception.

Solution 10 - Java

The JavaDoc for NullPointerException states:

> Thrown when an application attempts to > use null in a case where an object is > required. These include: > > * Calling the instance method of a null object. > * Accessing or modifying the field of a null object. > * Taking the length of null as if it were an array. > * Accessing or modifying the slots of null as if it were an array. > * Throwing null as if it were a Throwable value. > > Applications should throw instances of > this class to indicate other illegal > uses of the null object.

I consider violating the post-condition an illegal action. However, I think what exception you use doesn't matter much, because we are talking about a code path that should be (and hopefully is) unreachable, and hence you will not have error handling specific to that exception, and hence the only effect of that name is a different wording of some entry in a log file nobody is ever likely to see.

If in contrast you think the post condition is likely to be violated it might be a good idea to include more debugging information, such as the arguments the method was invoked with.

Solution 11 - Java

Absolutely YES.

Even JDK7 resolve this. See Objects#requireNonNull

void doWith(final Object mustBeNotNull) {

    // bush style
    if (mustBeNotNull == null) {
        throw new IllegalArgumentException("mustBeNotNull must not be null");

    // obama style
    if (mustBeNotNull == null) {
        throw new NullPointerException("mustBeNotNull must not be null");

    // kangnam style
    Objects.requireNonNull(mustBeNotNull, "mustBeNotNull must not be null");

    assert mustBeNotNull != null;

Solution 12 - Java

IMO you should never manually throw a NullPointerException. The calling routine wouldn't know if the real or manual NullPointerException without checking the description. In this case it looks like you would want to roll your own exception that matches the problem closer, so that the calling method can correctly recover frm this exception. Maybe a PostConditionException would be generic enough for many circumstances.

Solution 13 - Java

It's often a really good idea to throw NPE before the logic gets so deep that the calling programmer will have a hard time figuring out what was null. addListener() methods are a good example.

Uninformed downvotes notwithstanding, there are many methods in the JDK that do exactly this.

Solution 14 - Java

In the Java-verse null is always a valid value when expecting an object. You're better off avoiding such impossible post conditions. If you really can't abide a null then you'll have to rework your method so you can return a primitive.

Solution 15 - Java

As Joshua Bloch once said : "Null sucks!" :) whenever there is null is my face, I try to use the Optional that guava provides. The advantages are numerous to me.

Solution 16 - Java

> When there is a post-condition, that return value of a method must not be null, what can be done ?

A post-condition means that the method in question has a bug if the condition is not met. The way to express this in code is by using an assert on the post-condition. Directly throwing an exception, such as a NullPointerException or an IllegalStateException, would be a little misguiding, and hence misguided.

> Is it okay to throw NullPointerException programatically?

The Java API doc for the NPE says yes, but, judging by the votes given on this page, a 3:1 majority of developers says no. So I'd say it depends on the conventions in your workgroup.

The API doc first lists the cases where the JVM raises an NPE because code tries to invoke an operation on a null reference that requires an object of some sort (like calling a method or accessing a field), and null is not an object. It then states:

> Applications should throw instances of this class to indicate other illegal uses of the null object.

Interestingly, null is called an »object« here, which it is not. Which reminds me that the very name NullPointerException is bizarre for a language that doesn't have pointers. (That should probably have been NullReferenceException as in the Microsoft .NET class library.)

So should we dismiss the API doc on this count? I don't think so. The class library does use the NPE as described in the docs, for example in java.nio.channels:

> Unless otherwise noted, passing a null argument to a constructor or method in any class or interface in this package will cause a NullPointerException to be thrown.

This is not an NPE generated by the JVM, but a coded NPE with an attached error message stating which argument was null (like "in" is null!). (The code can be seen by doing javap -c -p java.nio.channels.Channels | more, looking for private static void checkNotNull.) And there are many classes that use NPEs in this fashion, essentially as a special case of IllegalArgumentException.

So after investigating this a bit and thinking about it, I find this to be a good use of the NPE, and hence I agree with the API doc and the minority of Java developers (as per the votes on this page) that you are both entitled and right to use the NPE in your own code in the same way the Java class library does, that is by providing an error message, which is conspicuously missing from JVM generated NPEs, which is why there's no problem telling the two kinds of NPE apart.

To address the minor point that the NPE will be thrown anyway further down the road: It can very well make sense to catch errors early instead of allowing the JVM to go on with the program, possibly involving disk or network I/O (and delays), and generating an unnecessarily large stack trace.

Solution 17 - Java

Yes, it is OK, but I would argue it's a better decision to just let it happen.

The problem with Java programmers and null is that people come from a C/C++ background, where NULL means something a lot different. In C/C++ dereferencing a NULL (or wild) pointer is a serious issue that can cause strange memory issues or crash your program (obvious not desirable). If you can get out of the C/C++ way of thinking and you realize that you have this extra layer, the JVM, which handles this condition for you, you start to think about NULL a little differently.

In C++ we have references, for instance, which can never be assigned NULL. In Java, there are no references, but Java object parameters behave more like C++ pointers. But there are a lot of situations in Java in which a method implicitly should NOT receive a null value for a parameter! So, what do we do?

The problem with treating null in Java like you do in C++ is that this results in null checks EVERYWHERE, whereas in C++ you would simply be declaring a method to take a reference, which explicitly states that it does not accept NULL. Pretty soon every method has to have a sanity check in it just to assert the condition of the program at that point, creating a mess.

It's a much better state of mind to work under the assumption that a method's default contract is that null is invalid for a parameter value.

Why? Well, let's look at what happens when such a method receives null as a parameter value. a) Perhaps it's OK because it does not dereference the value as part of its behavior. In this case, nothing happens. b) The value is dereferenced. In this case, the behavior from the JVM is exactly what we desire: an exception is thrown indicating that the contract of the method has been violated due to a parameter value being null, and it includes a stack trace bringing us all the way to the line in the method where the value is utilized in this way.

People take issue with NPE because they think that when you see NPE in the logs, it means "someone fucked up". But let's think about this for a second. What is actually the difference in NPE as an indicator of fuckup as opposed to expected behavior? I'd argue the major difference (and advantage) of using NPE as expected behavior is that it points not to the method in which it occurred, but to the caller for violating the method's contract. This is much more useful information. If we were to simply check null and throw a different exception, we might be under the false impression that the observed behavior is an expected error, when really the caller is violating the contract of the method. Congratulations, you correctly anticipated how you the caller might screw up in calling the method - however all you've done is led yourself astray as to what the real cause of the exception is - or at best, you're using two different exception classes to indicate the same thing and massively dirtying up the code with unnecessary garbage in the meantime.

So when it comes down to it people consider NPE to be taboo. Literally people will not allow it to be thrown because there's some sense of shame that goes with it - as if you aren't smart enough because you failed to guess where a value would be null. Well, I got news for you guys, you're just writing more useless code to do the same thing.

Some examples:

public void foo(Object o) {
  if (o == null) {
    throw new IGotchaException("HA! You're an IDIOT! I knew it!!");

public void foo(Object o) {;

^ Politically different. Functionally, not so much.

public void foo(int a, long b, double c, Object o) {
  if (o == null) {
    throw new IllegalArgumentException("Oh. Uh. Well, you've passed me null here. I... I'm not sure where to go from here because this object is kind of required for this function to do what it's supposed to do. Soooo... wouldja mind reworking your code a little bit so as to not pass null to this function as a parameter?! That'd be great thanks. Oh by the way, it's cause we deference o 40 lines below here");
  // ...

public void foo(int a, long b, double c, Object o) {
  // ...
  // NullPointerException, line 40, e.g. it wasn't OK to pass null for o you lunkhead

^ Maybe saves a few CPU cycles at the expense of a lot of annoying code. However, we do less comparisons in the second case.

public void foo(Object a, Object b, Object c, Object d) {
  if (a == null) throw IllegalArgumentException("jackass");
  if (b == null) throw IllegalArgumentException("jackass");
  if (c == null) throw IllegalArgumentException("jackass");
  // But d is totally OK!
  // ...

public void foo(Object a, Object b, Object c, Object d) {
  // ...
  // Throws null pointer exception if c is null, but not if d is null. Which is basically the same as above

^ The contract is implicit from the statement, rather than an exception case at the beginning of the method. Offers no other disadvantage.

public void foo(Object o) {
  if (o == null) {
  } else {

^ Bad

public void foo(Object o, int b) {
  Bar value = o.findSomethingWhichMayExist(b);
  if (value == null)

^ Using null return value to indicate the absence of a value. OK.

Another reason people have problems with NPE is because they don't know how to handle exceptions. NPE should never be a showstopper. The appropriate behavior is to catch RuntimeException, presumably at a much higher (or lower, depending how you see it) level in the call stack that traps it and reports it before "main". That is, assuming you're developing the sort of program that needs to be more resilient and can't just crash when an NPE happens.

Bottom line: don't ever expect it's a valid thing to be passing in null values for method parameters. And definitely don't create a contract for a method that explicitly accepts null and treats it as a valid value. But, allow null pointer exceptions to happen, and let the code fail, or not fail when it doesn't matter, naturally.

Solution 18 - Java

I agree with claim in the previous answers, that the NPE is bug in code and should not be thrown, but developer should fix unexpected null. However this state can be prevented most of time by tests.

The question was asked before 7 years, but now we have Optional in java 8 and this feature allow to prevent NPE.

The last one solution, which have on my mind is that you should check object on null and if it is equal, so throw your own exception with description of what happened.

Solution 19 - Java

Throw that exception is not a good practice in some case and I wonder why when you already catch it with the if statement?



All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionstratwineView Question on Stackoverflow
Solution 1 - JavaRomanView Answer on Stackoverflow
Solution 2 - JavawaxwingView Answer on Stackoverflow
Solution 3 - JavaTimo GeuschView Answer on Stackoverflow
Solution 4 - JavaDanubian SailorView Answer on Stackoverflow
Solution 5 - JavaAffeView Answer on Stackoverflow
Solution 6 - JavaGabView Answer on Stackoverflow
Solution 7 - JavaThorbjørn Ravn AndersenView Answer on Stackoverflow
Solution 8 - JavaTim BenderView Answer on Stackoverflow
Solution 9 - JavaRafe KettlerView Answer on Stackoverflow
Solution 10 - JavameritonView Answer on Stackoverflow
Solution 11 - JavaJin KwonView Answer on Stackoverflow
Solution 12 - JavaJerod HoughtellingView Answer on Stackoverflow
Solution 13 - Javauser207421View Answer on Stackoverflow
Solution 14 - JavaCurtainDogView Answer on Stackoverflow
Solution 15 - JavaEugeneView Answer on Stackoverflow
Solution 16 - JavaLumiView Answer on Stackoverflow
Solution 17 - JavaErichView Answer on Stackoverflow
Solution 18 - JavaPeter S.View Answer on Stackoverflow
Solution 19 - JavaTruong HaView Answer on Stackoverflow