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?
According to the language specification, a
throwstatement is defined as:And if the
Expressionevaluates tonull, then aNullPointerExceptionis thrown. Specifically,Since
NullPointerExceptionextendsRuntimeException, it is an unchecked exception. This could explain why there’s no compile-time error reported from this construct.