本文介绍了为什么是“throw null"?没有在 Java 中创建编译错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

class ThrowNull {
    public static void main(String[] args) {
        throw null;
    }
}

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

We know that rule for throw is throw ThrowableInstance;, where ThrowableInstance must be an object of type Throwable or a subclass of Throwable.

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

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.

那么为什么throw null;会在这段代码中编译?

So why would throw null; compile in this code?

推荐答案

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

throw Expression

如果 Expression 的计算结果为 null,则抛出 NullPointerException.具体来说,

And if the Expression evaluates to null, then a NullPointerException is thrown. Specifically,

如果对 Expression 的评估正常完成,产生一个 null 值,然后是 NullPointerException 类的实例 V'code> 被创建并抛出而不是 null.

由于NullPointerException 扩展了RuntimeException,所以它是一个未经检查的异常.这可以解释为什么这个构造没有报告编译时错误.

Since NullPointerException extends RuntimeException, it is an unchecked exception. This could explain why there's no compile-time error reported from this construct.

这篇关于为什么是“throw null"?没有在 Java 中创建编译错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-06 03:33