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

后端 未结 4 996
借酒劲吻你
借酒劲吻你 2020-12-05 17:25
class ThrowNull {
    public static void main(String[] args) {
        throw null;
    }
}

We know that rule for throw is throw ThrowableInst

相关标签:
4条回答
  • 2020-12-05 17:54

    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.

    0 讨论(0)
  • 2020-12-05 18:05

    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.

    0 讨论(0)
  • 2020-12-05 18:10

    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)
    
    0 讨论(0)
  • 2020-12-05 18:14

    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.

    0 讨论(0)
提交回复
热议问题