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

查看:208
本文介绍了为什么可以在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);
        }
    }
}

响应是: p>

The response is:

true  
false

对我来说这是相当惊人的。我会认为这会净化编译时错误。

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

为什么我可以在Java中抛出null,为什么会将其上传到NullPointerException?

(实际上,我不知道这是否是一个upcast,因为我抛出null)

除了真正非常愚蠢的面试问题(请不要在面试中问这个问题),我看不出有什么理由来 throw null 。也许你想被解雇,但这是...我的意思是,为什么还有人会将$ code> 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 ,但尝试的行为抛出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 检查其参数是否为null,如果为null,则会抛出 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'值。

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天全站免登陆