本文翻译自:Why can I throw null in Java? [duplicate]

This question already has an answer here: 这个问题已经在这里有了答案:

  • Why is “throw null” not creating a compilation error in Java? 为什么“ throw null”不会在Java中创建编译错误? 4 answers 4个答案

When running this: 运行此命令时:

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);}}
}

The response is: 响应为:

true
false

Which was fairly stunning for me. 这对我来说真是太棒了。 I would have thought this would net a compile-time error. 我本以为这会带来编译时错误。

Why can I throw null in Java, and why does it upcast it to a NullPointerException? 为什么我可以在Java中抛出null,为什么将其转换为NullPointerException?

(Actually, I don't know if it is an "upcast", given I'm throwing null) (实际上,鉴于我抛出的是null,因此我不知道这是否是“ upcast”)

Aside from a really really stupid interview question (please nobody ask this in an interview) I cannot see any reason to throw null . 除了一个非常愚蠢的面试问题(请没人在面试中问这个问题)之外,我看不到有任何理由throw null Maybe you want to be fired, but that's... I mean, why else would anyone throw null ? 也许您想被解雇,但这就是...我的意思是,为什么还有人会throw null呢?

Fun fact IntelliJ IDEA 12 tells me that my line, e instanceof NullPointerException , will always be false. 有趣的事实 IntelliJ IDEA 12告诉我,我的行e instanceof NullPointerException始终为false。 Which isn't true at all. 这根本不是真的。


#1楼

参考:https://stackoom.com/question/1BkYk/为什么我可以在Java中抛出null-重复


#2楼

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 . 看起来不是将null视为NullPointerException ,而是throw null 自身抛出throw null的行为将引发NullPointerException

In other words, throw checks that its argument is nonnull, and if it is null, it throws a NullPointerException . 换句话说, throw检查其参数是否为null,如果为null,则抛出NullPointerException

JLS 14.18 specifies this behavior: JLS 14.18 指定了以下行为:

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. 如果对表达式的求值正常完成,产生一个空值,则将创建并抛出类NullPointerException的实例V',而不是抛出空值。 The throw statement then completes abruptly, the reason being a throw with value V'. 然后,throw语句突然完成,原因是值为V'的throw。


#3楼

Don't know for sure, but I'm guessing that "throw null"; 不确定,但是我猜是“抛出空值”。 does not work, and trying it causes the program to throw an exception, and that exception happens to be (drum roll) NullPointerException... 工作,并试图导致程序抛出一个异常,并且该异常恰好是(鼓声)NullPointerException异常...


#4楼

It behaves in compliance with the JLS : 它的行为符合JLS的要求 :

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. 如果对表达式的求值正常完成,产生一个空值,则将创建并抛出类NullPointerException的实例V',而不是抛出空值。


#5楼

why does it upcast it to a NullPointerException? 为什么将其转换为NullPointerException?

As per JLS 14.18 : 根据JLS 14.18 :

A throw statement first evaluates the Expression. throw语句首先计算表达式。 If the evaluation of the Expression completes abruptly for some reason, then the throw completes abruptly for that reason. 如果对表达式的评估由于某种原因而突然完成,则抛出将由于该原因而突然完成。 If evaluation of the Expression completes normally, producing a non- null value V, then the throw statement completes abruptly, the reason being a throw with value 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. 如果对表达式的求值正常完成,产生一个非空值V,则throw语句突然完成,原因是带有值V的抛出。 如果对表达式的求正常完成,产生一个空值,则实例V' NullPointerException类的实例被创建并抛出,而不是null。 The throw statement then completes abruptly, the reason being a throw with value V'. 然后,throw语句突然完成,原因是值为V'的throw。

Why can i throw null in java ? 为什么我可以在Java中抛出null?

You can throw objects of type Throwable and since null is a valid reference for Throwable , compiler allows it. 您可以抛出Throwable类型的对象,并且由于nullThrowable的有效引用,因此编译器允许它。

This is what Neal Gafter says 这就是尼尔·古夫特(Neal Gafter)所说的

Although null is assignable to every reference type, the type of null is not itself a reference type. 尽管null可以分配给每种引用类型,但null类型本身并不是引用类型。 It was our intent that the requirement that the expression in a throw statement be a reference type was to be removed from the third edition of the JLS, but that change never actually made it into the published version. 我们的意图是从JLS的第三版中删除对throw语句中的表达式为引用类型的要求,但是该更改实际上并没有使其成为已发布的版本。 Thus, this is a javac compiler bug which I introduced in SE 5. 因此,这是我在SE 5中引入的javac编译器错误。


#6楼

Thinking about it this way makes it a bit more obvious as to why this works: 通过这种方式进行思考,使其在工作原理上更加明显:

try {Exception foo = null;if(false) {foo = new FileNotFoundException();} // Oops, forgot to set foo for the true case..throw foo;
} catch (Exception e){System.out.println(e instanceof NullPointerException);System.out.println(e instanceof FileNotFoundException);
}

为什么我可以在Java中抛出null? [重复]相关推荐

  1. java浮点数除以0_为什么用浮点数(或双精度)将数字除以零不会在Java中抛出java.lang.Arithmetic...

    下面的语句java.lang.ArithmeticException: / by zero很明显. System.out.println(0/0); 因为文字0被视为int文字,并且在整数算术中不允许 ...

  2. java异常在哪一层捕获_当在一个方法的代码中抛出一个检测异常时,该异常或被方法中的 ( )结构 捕获,或者在方法的 ( ) 中声明_学小易找答案...

    [填空题]当异常已经被定义时,必须通过( ) 语句来处理它. [填空题]Catch 子句包含( )的程序段 [单选题]下列java语言的常用异常类中,属于检测异常的是() [单选题]自定义异常类时,可 ...

  3. 程序中抛出空指针异常_从Java应用程序中消除空指针异常

    程序中抛出空指针异常 这篇文章简要介绍了Java 8的最有用但又"毫不夸张"的功能. 程序员花费了无尽的时间来纠正最常见但最危险的错误之一,即Null指针异常. 空指针异常会导致我 ...

  4. 获取线程中抛出的异常信息

    1 ScheduledExecutorService service = Executors.newScheduledThreadPool(10); 2 // 从现在开始delay毫秒之后,每隔一天执 ...

  5. 第8集析构函数中抛出的异常

    前两篇文章讨论了对象在构造过程中(构造函数)和运行过程中(成员函数)出现异常时的处理情况,本文将讨论最后一种情况,当异常发生在对象的析构销毁过程中时,又会有什么不同呢?主人公阿愚在此可以非常有把握地告 ...

  6. 第7集 构造函数中抛出的异常

    上一篇文章简单讨论了一下对象的成员函数抛出异常时的处理情况.本文中将继续讨论当在构造函数中抛出异常时,程序的执行情况又如何?这有点复杂呀!而且主人公阿愚还觉得这蛮有点意思! 构造函数中抛出的异常 1. ...

  7. 如何友好的处理 WebApi 中抛出的错误

    微软的 ASP.NET Web API 是一个轻量级的web框架,可用来构建基于 http 无状态的rest服务,异常是一种运行时错误,异常处理是一种处理运行时错误的技术,每一个开发者都应该知道如何处 ...

  8. 想抛就抛:Application_Error中统一处理ajax请求执行中抛出的异常

    想抛就抛:Application_Error中统一处理ajax请求执行中抛出的异常 参考文章: (1)想抛就抛:Application_Error中统一处理ajax请求执行中抛出的异常 (2)http ...

  9. getch计算机错误,为什么getch()在C中抛出一个错误

    我正在Windows XP中的Code :: Blocks中运行一个C程序. 我得到一个错误为什么getch()在C中抛出一个错误 "drawing operation is attempe ...

最新文章

  1. Strategy_Requirement1
  2. @Async的使用、原理及使用时可能导致的问题
  3. 梯度下降 最小二乘法 matlab,最小二乘法和梯度下降法的理解
  4. 最短路问题之Bellman-ford算法
  5. 【小白学习PyTorch教程】六、基于CIFAR-10 数据集,使用PyTorch 从头开始​​构建图像分类模型
  6. mysql数据库1067错误
  7. 使用nginx搭建https服务器
  8. 程序员达到高效率的一种境界
  9. linux 圣经软件,Ubuntu(Linux)下好用的中文圣经
  10. Amber Group与1Token达成合作,引入CAM系统加码机构级财务方案
  11. XMPP的简介和基本概念
  12. 如何看待开源软件的知识产权问题——陆首群
  13. ExtJs xtype一览(转存)
  14. git学习笔记-(3-linux基本命令)
  15. c语言qsort函数对结构体的一级排序,sort和qsort函数对结构体的二级排序
  16. php文件改后缀,php 如何修改文件后缀
  17. Android安装同应用不同版本,android一个应用如何在一个手机上装多个不同版本的方法...
  18. linux下无线网卡做热点,用ArchLinux做wifi热点无线路由
  19. AD20笔记-元器件绘制
  20. 微信小程序JSwxs获取当前时间戳

热门文章

  1. Android开发之WebView的开发使用(源代码分享)
  2. 轻松掌握ISO8583报文协议
  3. Android 修改Progressbar 旋转速度
  4. Flutter开发之AlertDialog、AboutDialog对话框组件-2(41)
  5. HTML5新增标签与属性
  6. vue 打印 canvas 显示空白
  7. 14、Docker监控方案(Prometheus+cAdvisor+Grafana)
  8. C# xml通过xslt转换为html输出
  9. 【JPA】注解@PostConstruct、@PreDestroy
  10. jmeter—操作数据库