gpt4 book ai didi

java - try-catch 场景 - 是否正确使用 checked 或 not

转载 作者:塔克拉玛干 更新时间:2023-11-01 22:28:50 26 4
gpt4 key购买 nike

我正在查看一个代码库,其中领域模型由许多嵌套的成员变量组成。

考虑这个场景

private static String getSomeStringRepresentation(A input) {
String result = "";
try {
result = input.getTypeA().getTypeAInfo().get(0).getRepresentation();
} catch (NullPointerException e) {
Logger.logDebug(e.getMessage());
}
return result;
}

在此调用链中,任何方法调用都可能导致 NullPointerException。在这种情况下用 catch 子句处理它是否正确?这是“可以处理异常”的情况吗?

编辑

四次检查 null 的情况真的很难看。在这种情况下,你不认为捕获 NPE 是合理的吗?

这里的问题是在一个可能为空的对象上调用一些方法。

最佳答案

为什么不检查 null 而不是放置一个 catch block ?捕获 NullPointerException 不被认为是好的做法。

If catching null pointer exception is not a good practice, is catching exception a good one?

还有

Is Catching a Null Pointer Exception a Code Smell?

关于java - try-catch 场景 - 是否正确使用 checked 或 not,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16231400/

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