Throwing null

April 30, 2003 4:21 PM

Question:

What does the following code do?

public class ThrowingNull {
    public static void main(String[] args) {
        ThrowingNull nully = new ThrowingNull();	

        try {
            nully.throwNull();
        } catch (Exception e) {
            System.out.println("Caught: " + e);
        }
    }

    public void throwNull() throws Exception {
        throw (Exception)null;	
    }
}

Answer:

Caught: java.lang.NullPointerException

A stacktrace points to the null being converted into an exception at the point it was being thrown (inside the throwNull method). I couldn't find anything explicit dealing with this case in either the Java Virtual Machine Specification, or the Java Language Specification. The closest seems to be Section 2.16.4 of the VM Spec, which lists various RuntimeException classes:

NullPointerException
An attempt has been made to use a null reference in a case where an object reference was required

Obviously, a throw clause requires an object reference (the exception), so passing null to it fits this criterion. It's more implicit than explicit though.

Update: Norman Richards points out that this is, in fact, documented in the JVM spec, under the athrow instruction. Therefore this behaviour is explicit and predictable albeit rather obscure.

If objectref is null, athrow throws a NullPointerException instead of objectref.

Previously: Mac vs PC. A parable.

Next: Movie Review: X-Men 2 (no spoilers)