gpt4 book ai didi

java - NullPointerException在哪里抛出?

转载 作者:行者123 更新时间:2023-11-30 08:08:33 25 4
gpt4 key购买 nike

如果我做这样的事情:

String str = null;
str.toLowerCase();

这里我会遇到一个NullPointerException,我想知道在哪里会创建异常。 JVM 是否管理此类情况并抛出 NullPointerException 或者在编译时在 com.sun.tools.javac.code.Type 类中对该情况进行一些检查?

我找不到一篇好的文章可以向我解释它,而且我也找不到与 OpenJDK javac 源中抛出运行时异常相关的任何内容。任何人都可以基础解释或链接到我可以阅读有关运行时异常创建的书籍\文章吗?

最佳答案

回答这部分我想知道哪里会创建异常?或标题本身哪里抛出NullPointerException?

It's is created on the same call Stack, which is the ordered list of methods that had been called to get to the method where the error occurred which then searches for a method that contains a block of code that can handle the exception (i.e exception handler).

Searching the call stack for the exception handler.图片来源 Oracle。

回答你的这一部分

或者在编译时对这种情况进行一些检查?

No

因为A检查异常。必须在代码中的某个位置捕获。如果没有,代码将无法编译。这就是为什么它们被称为检查异常。

自从

String str = null;
str.toLowerCase();

您将能够在不处理任何异常的情况下进行编译,因此不是检查异常(您可以在网络上查找更好的正式定义)。

现在您知道 NullPointerException 不是受检查的异常。

引用JSL

The unchecked exception classes (§11.1.1) are exempted from compile-time checking. i.e all the runtime exceptions

当方法检测到这些 RuntimeException 时,会抛出这些 RuntimeException,因为它在虚拟机运行时中遇到错误

关于java - NullPointerException在哪里抛出?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30734218/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com