Monday, January 28, 2008

The Subtle NullPointerException

Most NullPointerException's are blatantly obvious, like the attempted dereferencing of a null object. For someone like me who is well-rooted in C/C++, this is a completely natural thing to look for. Recently I discovered a type of NPE in Java that I wasn't ready for. Before I describe it, I'll ask a question: what happens when you pass a null Integer as an argument to a function that accepts int? Yep, NPE. What's a bit subtle about this NPE is that it happens in the context of the parent function. I.e. the stack trace does not reference the int-argument function---Java tries to convert a null Integer to int and fails, throwing an NPE as a result, before the int-argument function is called. Took me a bit of brain-thrashing before I realized what I had stumbled upon. 'course, the good thing is that once you've seen something like this once, you're unlikely to be tripped-up again. One change I've decided to make in my coding is to reduce/eliminate int function arguments. There's enough overhead in a function call to make the Integer/int choice a mute point. And, using Integer yields a more clear stack trace and makes clear that null's are a concern.

No comments: