throw null

Thursday, January 18th, 2007 03:45 pm
flwyd: (java logo)
[personal profile] flwyd

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.

May 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 2025

Most Popular Tags

Expand Cut Tags

No cut tags
Page generated Sunday, June 8th, 2025 06:20 am
Powered by Dreamwidth Studios