class ThrowNull { public static void main(String[] args) { throw null; } }
We know that rule for throw is throw ThrowableInstance;
, where ThrowableInstance
must be an object of type Throwable or a subclass of Throwable.
Simple types, such as int or char, as well as non-Throwable classes, such as String and Object, cannot be used as exceptions. null
is a special Java literal which represents a null value.
So why would throw null;
compile in this code?
Null can be assigned to any reference type. However, "the type of null" is not itself a reference type. The program compiles it because null can simply cast into Exception. And moreover throw looks for object reference after the declaration and as null can work as an object reference it displays the result.
NullPointerException is a RuntimeException . Runtime exceptions are critical and cannot be caught at compile time.
You can eliminate the exception by declaring the number of elements in the array before initializing it, as the following example does. For more information on declaring and initializing arrays, see Arrays and Arrays. You get a null return value from a method, and then call a method on the returned type.
According to the language specification, a throw
statement is defined as:
throw Expression
And if the Expression
evaluates to null
, then a NullPointerException
is thrown. Specifically,
If evaluation of the Expression completes normally, producing a
null
value, then an instance V' of classNullPointerException
is created and thrown instead ofnull
.
Since NullPointerException
extends RuntimeException
, it is an unchecked exception. This could explain why there's no compile-time error reported from this construct.
There are many things a compiler doesn't check, it assumes you do things for a good reason which it might not know about. What it does try to prevent is the common mistakes developers make.
It is possible some one thinks this is a good short hand for
throw new NullPointerException();
Integer i = null; try { i.intValue(); } catch (NullPointerException npe) { System.err.println("Caught NPE"); npe.printStackTrace(); }
and
try { throw null; } catch (NullPointerException npe) { System.err.println("Caught NPE"); npe.printStackTrace(); }
prints in Java 6 update 38
Caught NPE java.lang.NullPointerException at Main.main(Main.java:9)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With