flwyd: (java logo)
flwyd ([personal profile] flwyd) wrote2007-01-18 03:45 pm
Entry tags:

throw null

I saw some typo Java code in my CVS update today which called throw null. I wondered just what that would do. null can be cast to any object, so I thought it might get caught by the first catch clause. Alternatively, I thought it might escape all catch clauses (dangerous!). The answer?

	try {
	    throw null;
	} catch (IllegalArgumentException e) {
	    System.err.println("Caught IllegalArgumentException " + e);
	    e.printStackTrace();
	} catch (NullPointerException e) {
	    System.err.println("Caught NullPointerException " + e);
	    e.printStackTrace();
	} catch (Throwable t) {
	    System.err.println("Caught Throwable " + t);
	    t.printStackTrace();
	}

Caught NullPointerException java.lang.NullPointerException
java.lang.NullPointerException
	at TestStuff.main(TestStuff.java:156)

Java (even pre-1.5) automatically creates a NullPointerException if you throw null. It's like very specialized autoboxing.


Post a comment in response:

If you don't have an account you can create one now.
HTML doesn't work in the subject.
More info about formatting