The ubiquitous NullPointerException

Using any application of size, it’s almost inevitable that you’ll be slapped in the face time and time again with a bevy of NullPointerExceptions.

It’s hard to come up with a reasonable explanation of why these exceptions are so prevalent and commonplace. In fact, I have yet to come across a single application server that has never barfed out an NPE at some point or another.

Granted, in most cases it is the fault of the user; providing less than stellar input. J2EE descriptors are rather easy to get wrong, for example. You’d think though that a company that is able to muster up the resources to build a J2EE stack would be able to expend the fairly minimal amount of extra effort it takes to assume that users will pass in bad info, and handle it in a civilised and sociable manner.

JBoss (sorry, couldn’t resist) is a good example of that incredibly half-assed piss-poor lackadaisical approach. Very often, you get an NPE deep inside of JBoss code. The NPE is often repeated 3-4 times, wrapped inside of 2 or 3 other NPE’s. Sometimes you’re lucky and you actually get a helpful message that subtly hints of a vague area to begin sniffing around. Sometimes it’s particularly cruel and reports the wrong component entirely as the culprit, thus leading you on a wild goose chase familiar to those poor bastards trying to find decent documentation for any open source stuff.

Sadly, this particular ailment isn’t restricted to JBoss. JRun will also barf out endless reams of NPE’s if you so much as sneeze in its general direction. They also are of the ‘lets nest exceptions, it’s very helpful to end users’ school of thought that Weblogic now belongs to as well. Luckily, both of these servers will tend to hide that one crucial line of information describing the error you need in that behemoth of a trace. So if you do read it carefully, you might actually see it.

It really isn’t a very hard concept. Always expect bad input. If it can be entered into your code, then someone somewhere will enter it. Null checks are trivial and buy you a lot of love if they report clearly and coherently what is null, and why that’s bad. Don’t nest it, don’t obscure it, fail fast and helpfully.

19 Responses to “The ubiquitous NullPointerException”

  1. Kirill Says:

    Argeed, but have things to add: I’d say that one of the annoying issues with bad (invalid/incomplete) data is inability of most programs to keep that data. A typical reaction on entering of an invalid data is basically a modal “stop now and make it correct!!!” without any reasoning if that “validity” is required right now or not. Moreover, that data is not going to be saved (for further correction may be). It just says: “make it correct or forget about that — cannot save!”

  2. Sam Says:

    In some circumstances saving ‘invalid’ data may be possible, but in many its not. Some methods of data storage rely on the data itself being in a valid format – databases, CSV files etc. Granted this isn’t always the case.

  3. Bas Scheffers Says:

    Oh My God. You are seriously suggesting you save _invalid_ data, in the vain hope that someone corrects it later, before you try to process it in some job, like, ehrm, your company’s payroll run?

    This reminds me of the “other” Y2K problem, when things put of “indefinitely” were entered as year 99 or 00…

  4. Mats Henricson Says:

    Error handling is neither well understood or appreciated by engineering management, so working hard on such issues within a particular code base is not fun. I spent a long time on it at a previous job, and I had to convice pretty thick managers that it was important. It almost cost me my job, because it seemed like I wasn’t working on important issues.

  5. Anonymous Says:

    Well duh!

    So guess what the problem is with your suggestion, it you discover invalid data what then will you do? Throw another kind of exception????!

  6. Sam Says:

    Well, if you are saving data as part of a process, the saving invalid data would be ok as the process itself can be marked as ‘unfinished’.

  7. Anonymous Says:

    First post!!!!!!!!!!!!!!!!!!!!!!

  8. Jeff Waltzer Says:

    Wish more people would use the Null Object Pattern.
    Don’t set your values to null. Make a new class with the same interface that does logical things for a unitialized object. (ie return blank fields or throw your own Exceptions)

  9. Dave Says:

    Null Object Pattern can mask NullPointerExceptions. That’s like trapping SIGSEGV and doing nothing. Yeah, you won’t get exceptions, but you also won’t find out where you code is wrong. If your code throws NullPointerException IT IS WRONG. It’s not that fucking hard to check if somnething’s null. Yes, it’s a pain in the ass, but you only need to check each object once, and really, error handling is what makes programming hard. Anyone can write a program that works properly in the best case. Working with bad input is what the challenge is.

    And also, if you are using Null Object Pattern, at some point you have to CHECK FOR NULL to set your variable to the magic golden hammer Null Object, so it really buys you nothing if you are coding properly and CHECKING FOR NULL.

  10. Craig Says:

    Hani:”Boss (sorry, couldn’t resist) is a good example of that incredibly half-assed piss-poor lackadaisical approach. Very often, you get an NPE deep inside of JBoss code. The NPE is often repeated 3-4 times, wrapped inside of 2 or 3 other NPE’s.”

    Well it’s open source, so feel free to find it, fix it and submit a patch.

  11. Bas Scheffers Says:

    Dave, I don’t think you get it. If I read Hani’s description correctly, the error is deep down somehwere in someone else’s code. Presumably because you haven’t configured something properly or didn’t use the API properly. (but there is that OS documentation again…) But if something shouldn’t be null, how f***ing hard is it do:

    if (foo == null) {throw new NullPointerException(“Please make sure xxx is defined”);}

    At least then you give people a clue as to what is going on.

    And then there are the ones you couldn’t help. Some idiot puts a try with a catch that does nothing and then the next operation fails on a NPE, then how the hell are you supposed to figure out it is because because the remote JMS server it was trying to communicate to barfed and reset the TCP connection?

  12. Bas Scheffers Says:

    Sorry Dave, I meant Jeff. And the rest of the rant was in general, for those who think this is just about checking field on web pages. Yes, there are other types of programming to be done in Java than just take some info from a form, put it in a database and pull it out to display it again…

  13. Kirill Says:

    >So guess what the problem is with your suggestion, it you discover invalid data what then will you do? Throw another kind of exception????!

    Just show a good, readable explanation why your program cannot proceed. Explictly point to places where corrections are needed.

    The point is that it’s not always required at the time of data typing. The program should not scream about the user’s error if it doesn’t stop from making a next step.

    Most programmer prefer writing stupid modals instead.

  14. Ross Judson Says:

    What pisses me off is library writers who let nulls get thrown, then catch them and do something else. Or people who use array-out-of-bounds exceptions to expand arrays. That is just frickin’ stupid. It makes debugging any application that uses the library a pain in the ass to debug, as you have to set up all kinds of breakpointer filters to mask out the spurious, stupidly thrown exceptions.

  15. TDD Says:

    Basically, you boil down to the Robustness Principle: “Be liberal in what you accept (as input, as plug-in behavior…), and conservative in what you do.”

  16. boxed Says:

    Win32 API is full of these kinds of problems. API functions that have 10 (I’m not kidding) parameters that return 0 on failure and when you call GetLastError() to get the error code, you get, INVALID_PARAMETER. WHICH parameter for the love of God?! Aarrgh

  17. No one Says:

    if (foo == null) {throw new NullPointerException(“Please make sure xxx is defined”);}

    Yeah, that’s preventing NullPointerExceptions, isn’t it? :)

  18. Craig Pfeifer Says:

    No it’s not preventing it, but at least it gives you some idea of what went wrong and what you might be able to do to prevent it from happening in the future.

  19. Anonymous Says:

    No shit, No One, it’s diffucult to “guess” what a user might input.

Leave a Reply