Why is "throw null" not creating a compilation error in Java?

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 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 class NullPointerException is created and thrown instead of null .

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)

我认为,因为Null可以投入到任何类型的引用中,所以在编译时它没有错,如果你抛出null而不是throwable。

链接地址: http://www.djcxy.com/p/73626.html

上一篇: 转换时出现Java编译时错误

下一篇: 为什么“throw null”不会在Java中创建编译错误?