gpt4 book ai didi

java - 多个 catch block 和 continue 运算符

转载 作者:行者123 更新时间:2023-12-01 22:17:51 26 4
gpt4 key购买 nike

我在使用带有异常的多 catch block 时遇到了一个问题,该异常可以应用于同一事件。请看下面的代码:

for (String currentString : stringsList) {
try {
Long.valueOf(currentString);
} catch (NullPointerException e) {
//do smth;
continue;
} catch (NumberFormatException e) {
//do smth;
continue;
}
//do smth;
}

想法如下:如果当前字符串变量为 null,则执行特定操作并完成当前迭代,而不检查 NumberFormatException。但事实证明,当 currentString == null 时,下一个 catch block 无论如何都会被满足。我不明白为什么 continue 在这种情况下不起作用并且没有留下第一个 catch block 。下一个解决方案是 Not Acceptable ,因为它不允许执行代码保留在循环中:

for (String currentString : stringsList) {
try {
Long.valueOf(currentString);
} catch (NullPointerException e) {
//do smth;
break;
} catch (NumberFormatException e) {
//do smth;
} finally {
continue;
}
//do smth;
}

我找到了解决方案,但它并不优雅:

for (String currentString : stringsList) {
if (currentString == null) {
//do smth;
continue;
}

try {
Long.valueOf(currentString);
} catch (NumberFormatException e) {
//do smth;
continue;
}
//do smth;
}

如果有人知道如何解决这个问题,我将非常感谢您的建议。预先感谢您。

更新真的很抱歉,但这是我的错。 Long.valueOf(null) 也会抛出 NumberFormatException 。感谢所有的评论。我当前的解决方案是:

 for (String currentString : stringsList) {
try {
Long.valueOf(currentString);
} catch (NumberFormatException e) {
if (currentString != null) {
//do smth;
}
continue;
}
//do smth;
}

最佳答案

Long.valueOf 不会抛出 NullPointerException。

在 Long 源代码中,您将看到 valueOf 方法调用了 parseLong 方法。

此方法检查 null 并抛出 NumberFormatException(请参阅下面的代码片段)

public static long parseLong(String s, int radix)
throws NumberFormatException
{
if (s == null) {
throw new NumberFormatException("null");
}

所以你必须这样做

if (currentString == null) {
//do smth;
continue;
}

关于java - 多个 catch block 和 continue 运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30618094/

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