Is it okay to throw NullPointerException programmatically? [closed]
Asked Answered
E

19

62

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

if(returnValue==null)
      {
           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?

Eugene answered 23/7, 2010 at 21:46 Comment(1)
On the choice between using assert or a null check: assume that assert is only used in development environments, and that asserts are only sanity checks for you or other developments. Null checks on the other hand are for all kinds of client interaction (either with a user or someone else using your code, as in a public API), and run at runtime on all environments.Ladyinwaiting
A
44

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.

Antiquary answered 24/7, 2010 at 23:10 Comment(1)
In the case of a null argument IllegalArgumentException might be the more appropriate exception to throw. NullPointerException is meant to indicate that an attempt was made to perform some operation on a null value. If an NPE is what you are aiming for, then just forgo null checking in your method, and the NPE will be thrown by the JVM naturally.Sexist
O
74

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.

Ochs answered 23/7, 2010 at 23:6 Comment(7)
Actually NullPointerException is a great way to tell, that an argument should not be null. See Effective Java: 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.Varian
Take a look at the javadoc: Applications should throw instances of this class to indicate other illegal uses of the null object. That's pretty clear to me. Throwing NPEs is legal and valid and should be done for every non-null parameter when null is passed in. Period.Varian
@willi,keeping npe's to be only thrown by the runtime not your own code, makes it easy to determine how serious a npe is.Skelton
I agree with whiskeysierra. A NPE is the way to tell that some method parameter was null, and is the perfect exception for it. Not IllegalArgumentException. Also throwing it in your own code is not different from a NPE thrown in Java library code. I code by contract and therefore the user of my method gets what he should expect if he read my method's Javadoc. Throwing it prevents the code to execute further (fail early); otherwise it will fail anyway in a place that is totally unrelated to where the actual bug is located. NPEs should always be taken serious as it indicates a programming error.Indifference
@ThorbjørnRavnAndersen Any NPE is serious.Barrier
Ultimately this is a discussion for softwareengineering.SE, but with respect to using code as a way to model behavior, throwing an NPE is not helpful, despite the documentation. Take it from seasoned computer scientist C. A. R. Hoare, who calls the sheer invention of the null reference his "billion dollar mistake." What is better than throwing an NPE is informing the caller why the input was invalid. It is good to say that the input was null, but it is better to say that the argument is invalid because null is not a valid option.Phenacetin
I think, as many have pointed out, the javadoc is a good place to look at how to use these two types of exceptions. In particular, a functioning example is java.util.TimeZone getDisplayName(Locale locale) throws an NPE for null arguments but getDisplayName(boolean daylight, int style) throws an IAE for integers outside of the expected valid list. This is a very important distinction. Some arguments can never be null, simple types like boolean and int in this case. Here, only an IAE can be thrownGinnygino
A
44

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.

Antiquary answered 24/7, 2010 at 23:10 Comment(1)
In the case of a null argument IllegalArgumentException might be the more appropriate exception to throw. NullPointerException is meant to indicate that an attempt was made to perform some operation on a null value. If an NPE is what you are aiming for, then just forgo null checking in your method, and the NPE will be thrown by the JVM naturally.Sexist
G
30

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.

Gish answered 23/7, 2010 at 21:49 Comment(0)
E
16

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.

Ewall answered 22/3, 2013 at 16:4 Comment(4)
I think that is not correct. It is true that NullPointerException means that I have forgotten to check something. But when it is directly thrown by a method the bug is actually there if it is forbidden to pass in null. So the only good way is to throw NPE.Mitman
The problem is that if you throw it deliberately as per this question and as per innumerable example in the JDK, your first sentence isn't true.Barrier
This is fine to throw NPE when you are in such a condition where a value is null and recommended by official java doc, plz check the following link. docs.oracle.com/javase/6/docs/api/java/lang/…Herzl
If the exception is reaching me as a developer (not being caught), I normally look at the exception message more than the exception's name. I'd use Objects.requireNonNull which will throw an NPE, but make sure to include a message so it's clear to see what was null.Becalm
S
8

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!

Supernatant answered 23/7, 2010 at 22:12 Comment(2)
This particular example would hopefully be caused by an empty ProdCode input field?Skelton
If only, that would at least sort of make sense. This is how a contract dev I worked with was handling the result of a search based on user input.Supernatant
H
6

http://pmd.sourceforge.net/pmd-5.0.1/rules/java/strictexception.html
"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."

Habakkuk answered 22/3, 2013 at 15:31 Comment(2)
Anyway oracle doc say something different. docs.oracle.com/javase/tutorial/essential/exceptions/… But i must tell that i disagree with about all of the above article content.Habakkuk
Is there a reason why any number of people here should agree with an arbirtary opinion on an arbitrary SourceForge project? And why should 'most people assume' anything when the actual cause is right there in the stack trace?Barrier
Q
5

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.

Quintain answered 23/7, 2010 at 23:0 Comment(0)
C
4

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).

Chopfallen answered 24/7, 2010 at 6:32 Comment(0)
A
3

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.

Anchor answered 23/7, 2010 at 21:51 Comment(5)
Erm, simply because some unnamed book uses this definition does not make it a universally accepted one - especially if it contradicts the JavaDoc of that exception.Surfboarding
From the java documentation, "Thrown when a program tries to access a field or method of an object or an element of an array when there is no instance or array to use, that is if the object or array points to {@code null}. It also occurs in some other, less obvious circumstances, like a {@code throw e} statement where the Throwable reference is {@code null}."Anchor
Where in the Java documentation ...? The JavaDoc to that exception ends with "Applications should throw instances of this class to indicate other illegal uses of the null object."Surfboarding
What JavaDoc are you looking at? docjar.com/docs/api/java/lang/NullPointerException.html takes its info from JavaDoc. You're misinterpreting what you get from the website you call JavaDoc, which is actually more along the lines of a wiki. None of those cases have anything to do with returning a null value.Anchor
Interesting that the Apache Harmony project would choose to provide a different javadoc than the Sun implementation of the JDK, to which I linked (that the link is no longer hosted at sun is really Oracle's fault). Note that according to their website, Apache Harmony is not a certified implementation of Java. In fact, they don't claim to be fully compatible with it.Surfboarding
S
3

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.

Surfboarding answered 23/7, 2010 at 22:3 Comment(0)
H
2

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;
}
Horatio answered 8/2, 2013 at 6:4 Comment(0)
F
1

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.

Finnigan answered 23/7, 2010 at 23:21 Comment(2)
totally agree, it should be thrown by JVM. We should catch it and handle.Deadandalive
I totally disagree. A null value in à context where it is not expected should yield a NPE. THE advantage of throwing it yourself is that you can add à usefull message in it.Trifolium
B
1

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.

Barrier answered 24/7, 2010 at 10:34 Comment(0)
F
0

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.

Fleuron answered 24/7, 2010 at 7:47 Comment(0)
K
0

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.

Killough answered 18/2, 2013 at 11:40 Comment(2)
Curious where he said thatBambara
@Bambara Or if he said it, or why it makes a difference if it disagrees with the official documentation.Barrier
N
0

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.

Newcomen answered 3/2, 2014 at 13:21 Comment(0)
B
0

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!!");
  }
  o.bar();
}

public void foo(Object o) {
  o.bar();
}

^ 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");
  }
  // ...
  o.doSomethingWithA(a);
}

public void foo(int a, long b, double c, Object o) {
  // ...
  o.doSomethingWithA(a);
  // 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!
  // ...
  c.setSomeValueThatMayBeNull(d);
}

public void foo(Object a, Object b, Object c, Object d) {
  // ...
  c.setSomeValueThatMayBeNull(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) {
    doTheBoogie();
  } else {
    doTheRobot();
  }
}

^ Bad

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

^ 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.

Bornie answered 29/6, 2017 at 10:8 Comment(2)
It isn't 'a better decision to just "let it happen"' if the result is a more obscure problem than just throwing the NPE at the earliest opportunity. Consider adding a Listener for example: checking for null is a lot more opportune than letting the listener-calling thread encounter an NPE later on and printing an osbscure strack trace that is miles removed from the site of the problem.Barrier
EJP in this case I'd throw a java.lang.IllegalArgumentException because the criterion for creating the listener is non null.Bornie
S
0

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.

Sheldon answered 4/10, 2017 at 18:51 Comment(0)
D
-1

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

if(returnValue==null)

Deadandalive answered 24/7, 2010 at 1:53 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.