Surprise nullpointerexception!

Last week I had to modify a JSP file. It wasn’t something I’d done before but the author of it made clear that they weren’t going to support it, so I gave it the old college try. My rationale was that I have experience with about a dozen different scripting/programming languages and, combined with syntax references, I had a chance of figuring out how to modify the code.

When I looked into it I found this:


if ((bipvar == null) || (bipvar.length() == 0)) {
redir = "a URL";
} else {
throw new RuntimeException("The bip parameter is not currently supported");
}

It worked fine, but I needed to add a third case. I decided to separate the condition that throws an exception and move it earlier in the code (if it’s going to throw an exception, there was no point in having the code do some other actions that it does.) The result was:


if ((bipvar != null) || (bipvar.length() == 0)) {
throw new RuntimeException("The bip parameter is not currently supported");
}
.
.
.
if ((pfs == null) || (pfs.length() == 0)) {
redir = "one URL";
} else {
redir = "another URL";
}

The problem was, this produced one of two results – either the intentionally thrown exception, or a null pointer exception. Ultimately, I had to rewrite it as below to make it work.


if ((bipvar != null)) {
throw new RuntimeException("The bip parameter is not currently supported");
}
.
.
.
if ((pfs == null)) {
redir = "one URL";
} else {
redir = "another URL";
}

Additionally, in the course of debugging I noticed that out.println bipvar;" worked while out.println bipvar.length(); did not.

With the previously stated caveat that I am unfamiliar with JSP, can anyone explain why this is so? In particular, why it would work with a .length() used in an if condition once but not twice.

This entry was posted in Uncategorized. Bookmark the permalink.
  • Vicky

    Have you typoed something there?
    It looks like you went from:
    if (a || b)
    to:
    if (!a | b)
    when I assume you meant
    if (!a && !b)
    (as in de Morgan’s law).

    • Vicky

      Duh, please pretend my second if had a double || for the or. I can’t edit it.

    • Danielle White

      You are correct; that was a logic error on my part which was not detected because I hit the NPE error which required removing the b condition.

    • Danielle White

      And I missed your point, in the way that was causing the NPE, just not in the way I was thinking – because it was null it was trying to check the length.