运行此命令时:

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

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

Why can I throw null in Java, and why does it upcast it to a NullPointerException?

(Actually, I don't know if it is an "upcast", given I'm throwing null)

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

Fun fact IntelliJ IDEA 12告诉我,我的第e instanceof NullPointerException行永远是假的.这根本不是真的.

推荐答案

看起来并不是null被视为NullPointerException,而是try throw null itself的行为抛出了NullPointerException.

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

JLS 14.18 specifies此行为:

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

Java相关问答推荐

Gmail Javi API批量处理太多请求

当耗时的代码完成时,Circular ProgressIndicator显示得太晚

Java应用程序崩溃时试图读取联系人从电话

CAMEL 4中的SAXParseException

如何使用AWS CLI从S3存储桶中的所有对象中删除用户定义的元数据?

滚动视图&不能在alert 对话框中工作(&Q;&Q;)

Spring Data JPA慢慢地创建了太多非活动会话

Spring @Value default无法计算表达式

SonarLint:只能有条件地调用方法(S)

当b是一个字节并且在Java中值为-1时,为什么b>;>;>;1总是等于-1?

try 在两个不同数组的数字之间求平均值

在不使用instanceof或强制转换的情况下从父类变量调用子类方法

在应用程序运行时更改LookAndFeel

在线程Java中调用Interrupt()之后调用Join()

如何调整JButton的大小以适应图标?

如何在ApacheHttpClient 5中为单个请求设置代理?

使用@ExceptionHandler的GlobalExceptionHandler还是来自服务器的REST应答的ResponseEntity?

为什么我的登录终结点不能被任何请求访问?

Java递归泛型是否可以被视为继承和重写的语法糖

如何正确使用java.time类?