views:

179

answers:

2

This snippet throws an NullPointerException due to the fact that its unboxed to a primitive type and Long.longValue() is called, right?

Thats even easy to see if you have a snippet like this:

long value = (Long) null;

But the NullPointerException is even harder to get in a more complex situation like this:

long propertyValue = (Long) obj.getProperty(propertyModel.getName());

So isn't there any possibility for the Java-Compiler to make a more comfortable Exception out of this? I would prefer an IllegalArgumentException with a message like "You're trying to cast a null-Object into a primitive type, this can't be done!"

Wouldn't this be more appropirated? What do you think? Is this even possible at runtime? Are we able to determine this cast? I didn't looked at the java bytecode until yet. Maybe this supports any solution.

This question can be answered: I like to now if its possible to achieve this behaviour!

+1  A: 

That's not what IllegalArgumentException means. The compiler has no guarantee that the value will be null until runtime. All it knows is the type, which in your example is likely to be String.

Certainly at runtime, when the exception is thrown, the compiler knows that the problem is a null value. You can see this yourself if you're using a debugger. So from a technology standpoint -- and here is the short answer to your question -- yes, it would be possible to create a compiler that will include that in the error description. But if you want a special message for null values, what's next? Special messages for integers that are outside some acceptable bound by more than 10? Admittedly that's kind of a silly example, but I hope it's illustrative.

Lord Torgamus
The return type in my example is Object, would it be String i could use Long.valueOf(). Its not forced to be an IllegalArgumentException. I would like a special Exception because there is done some magic for people don't knowing the boxing/unboxing. But okay, its your opinion :)
codedevour
I don't understand what you mean about forcing and magic, but if you have a more specific problem, please post additional sample code. Information like the types of variables would be especially useful.
Lord Torgamus
+1  A: 

According to the Java language specification, unboxing happens via calling Number.longValue(), Number.intValue(), etc. There is no special byte code magic happening, it's exactly the same as if you call those methods manually. Thus, the NullPointerException the the natural result of unboxing a null (and in fact mandated by the JLS).

Throwing a different exception would require checking for null twice during every unboxing conversion (once to determine whether to throw the special exception, and once implicitly when the method is actually called). I suppose the language designers didn't think it useful enough to warrant that.

Michael Borgwardt