有人可以解释为什么这个 NullPointerException 修复有效吗?

问题描述 投票:0回答:1

我的应用程序解析 .xml 文件并将其转换为 Kotlin 类。它基于 XSD 文件构建 JavaClass。 NonNull 属性之一为 null,这导致了未捕获的异常。所以我决定将它包装在 try..catch 中,以便我们捕获它并打印附加信息。但是,我在调用该函数的行上遇到了 NullPointerException。

实现1(函数调用上的NPE,未捕获):

private fun Message.statusInformation(body: StatusBody) = try {
            this.statusInformation //Function marked as @NotNull in generated Javacode
        } catch (e: NullPointerException) {
            //Logging and throwing a different exception
        }

实现2(NPE被捕获在handler中):

private fun Message.statusInformation(body: StatusBody): StatusInformation = try {
            this.statusInformation //Function marked as @NotNull in generated Javacode
        } catch (e: NullPointerException) {
            //Logging and throwing a different exception
        }

从调用者的角度来看,类型仍然是 StatusInformation,但第二个实现按预期工作。

有人可以解释为什么将返回类型添加到表达式中可以防止无法捕获的 NPE 吗?或者在哪里可以找到这方面的文档,我找不到任何。

kotlin nullpointerexception expression
1个回答
0
投票

在实现 1 中,您没有显式说出返回类型,因此 Kotlin 尝试推断返回类型,但此方法类似于

NotNull
,因此如果它返回
null
,则
NullPointerException
错误会发生在
try -catch 之前
因此错误未被捕获。

在实现 2 中,您声明返回类型,然后 Kotlin 处理

try-catch
内的所有内容,这就是为什么它可以检测
NullPointerException
块中的
catch

© www.soinside.com 2019 - 2024. All rights reserved.