为什么我可以在 Java 中抛出 null? [英] Why can I throw null in Java?

查看:27
本文介绍了为什么我可以在 Java 中抛出 null?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

运行时:

public class WhatTheShoot {

    public static void main(String args[]){
        try {
            throw null;
        } catch (Exception e){
            System.out.println(e instanceof NullPointerException);
            System.out.println(e instanceof FileNotFoundException);
        }
    }
}

回复是:

true  
false

这对我来说相当惊人.我原以为这会导致编译时错误.

Which was fairly stunning for me. I would have thought this would net a compile-time error.

为什么我可以在 Java 中抛出 null,为什么它会向上转换为 NullPointerException?

(实际上,我不知道它是否是向上转换",因为我抛出的是 null)

除了一个非常愚蠢的面试问题(请不要在面试中问这个)我看不出有任何理由要throw null.也许你想被解雇,但那是......我的意思是,为什么会有人throw null?

Aside from a really really stupid interview question (please nobody ask this in an interview) I cannot see any reason to throw null. Maybe you want to be fired, but that's... I mean, why else would anyone throw null?

有趣的事实 IntelliJ IDEA 12 告诉我,我的台词,e instanceof NullPointerException,将始终为 false.这根本不是真的.

Fun fact IntelliJ IDEA 12 tells me that my line, e instanceof NullPointerException, will always be false. Which isn't true at all.

推荐答案

看起来不是将 null 视为 NullPointerException,而是尝试的行为throw null 本身会抛出一个NullPointerException.

It looks like it's not that null is treated as a NullPointerException, but that the act of attempting to throw null itself throws a NullPointerException.

换句话说,throw 检查其参数是否为非空,如果为空,则抛出 NullPointerException.

In other words, throw checks that its argument is nonnull, and if it is null, it throws a NullPointerException.

JLS 14.18 指定此行为:

JLS 14.18 specifies this behavior:

如果表达式的计算正常完成,产生一个空值,则创建并抛出一个 NullPointerException 类的实例 V' 而不是 null.然后 throw 语句突然完成,原因是值为 V' 的 throw.

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. The throw statement then completes abruptly, the reason being a throw with value V'.

这篇关于为什么我可以在 Java 中抛出 null?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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