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?
I think because Null can be cast in to any type of reference.so in compile time its nothing wrong if you are throwing null instead of throwable.
In generel, and not just throw. Any object variable can be assigned null. So we can see that throw is not a special case. Should it be? maybe. Is it consistent? Yes.
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
and
prints in Java 6 update 38
According to the language specification, a
throw
statement is defined as:And if the
Expression
evaluates tonull
, then aNullPointerException
is thrown. Specifically,Since
NullPointerException
extendsRuntimeException
, it is an unchecked exception. This could explain why there's no compile-time error reported from this construct.