throw null

Jan 18, 2007 15:45


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.

programming, java, null

Previous post Next post
Up