为什么“抛出空”不会在Java中创建编译错误? [英] Why is "throw null" not creating a compilation error in Java?

查看:130
本文介绍了为什么“抛出空”不会在Java中创建编译错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

$ $ $ $ $ $ $ $ $ $ $ $ $;;;;;;;;;;;;;;;;;;;;;;;;;;;
}
}

我们知道throw的规则是 throw ThrowableInstance; ,其中 ThrowableInstance 必须是Throwable类型的对象或Throwable的子类。



简单类型(如int或char)以及非Throwable类(如String和Object)不能用作异常。 null 是一个特殊的Java文字,表示一个空值。



那么为什么 throw null; 在此代码中编译?

解决方案

根据语言规范,一个 throw 语句定义为:

  throw Expression 

如果 Expression 评估为 null ,那么抛出一个 NullPointerException 。具体而言,


如果表达式的评估正常完成,则生成 null value,然后创建并抛出类 NullPointerException 的实例 V'而不是 null


由于 NullPointerException extends RuntimeException ,它是一个未经检查的异常。这可以解释为什么没有从这个结构报告编译时错误。


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.

这篇关于为什么“抛出空”不会在Java中创建编译错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆