Thursday, June 10, 2010

throw null

My colleagues told me of some code they came across which included the statement: "throw null".

I'd never seen that before - I didn't know what it would do or even if it was valid.

I'll let you think about it. Have a go if you want to check your answer:

public class Surprise {
public static void main(String[] args) {
throw null;

Copyright © 2010 Ivan Moore


Markus Gärtner said...

Wow, that's fascinating:

public class TestThrowsNull {

public void nullTest() throws Exception {
try {
new ThrowsNull();
fail("should have thrown a null");
} catch (NullPointerException e) {


private static class ThrowsNull {
public ThrowsNull() {
throw null;

Unknown said...

Indeed, throws a NPE - short for:
new NullPointerException()

Gino A Melone said...

Let's be clear. It throws the NPE because throw implicitly tries to access a member of the thrown exception in some way.

keithb said...

So, my first thought was that the construct is plainly valid but that I had no idea what it would do.

throw expects a reference to the object to be thrown, and null is a reference to an object. throw more specifically expects a reference to an object that's an instance of a subclass of Throwable, which null also is, kinda.

The type of null should be something like (reference to) ⊥, the type which is the subtype of every other type. (⊥ by definition has no instances). ⊥ is what should really be the return type of main, as main doesn't return a value. The return type is actually "void" as we know, and if Java were consistent I'd expect null to be (a reference to) the unique instance of void. But it isn't, because it isn't. There is a separate "null type". It's no surprise that this bears a close resemblance to C's type "void *" because Java does by god have pointers.

I suspect that the magic is at the receiving end, things which accept references to objects know to accept null, rather than that null is an especially clever value.

I also tend to agree with GinoA that we eventually see a NullPointerException because something in the runtime tries to do something with the null. I'd be suspicious of production code that relied on "throw null" as a synonym for "throw new NullPointerException()"

Like all the best authoritarian regimes, Java only lies to us for our own good.

Mike Roberts said...

Fascinating indeed!

Unknown said...
This comment has been removed by the author.
Unknown said...

yep, I saw this on a project last year. The interesting puzzle for me is just what the person that wrote the code was thinking when they did it.
Were they trying to be extra clever? extra lazy? what

Kevin Peel said...

You wrote that code !!!!