【发布时间】:2019-03-01 20:31:39
【问题描述】:
我试图弄清楚如何在我的代码中捕获一个 numberformat 异常错误,这样如果用户在字符串中输入一个字母并且我的程序尝试将它解析为一个 int 我的程序就不会抛出一个错误而是停止并返回一个布尔值。我也试图理解,如果 try 语句有效,我希望它继续执行以下代码。
if (counter == 3) {
int compare;
boolean check = true;
String[] newip = IpAddress.split("\\.");
if (newip.length == 4) {
for (int index = 0; index < newip.length; index++) {
//There should be a try statement here.
// if the try statement fails then I'd like for it to catch
// the numberformatexception and evaluate my boolean to
//false;
//but if it passes I'd like for it to continue to execute
//the following code.
compare = Integer.parseInt(newip[index]);
if (compare >= 0 & (compare <= 255)) {
check = true;
}
else{
check = false;
}
}
if (check)
return true;
else
return false;
}
else {
check = false;
return check;
}
}
else{
return false;
}
}
【问题讨论】:
-
尝试可能抛出异常的代码,在catch块中,在出错的情况下做你想做的事(在你的情况下
return false) -
请(重新)阅读您的 Java 指南,了解
try语句是什么以及它是如何工作的。 -
@Andreas 我认为这里不需要 try-catch 块。由于输入的字符串必须是整数,他/她应该只检查是否只有数字存在。另一个故事,如果输入的值被格式化,但那是题外话
-
@LppEdd "应该只检查是否只有数字存在" 这还不够,因为即使字符串是所有数字,也可以抛出
NumberFormatException,即如果字符串超过int的范围。 -
@LppEdd 您如何认为这不是“要求”? OP 希望程序 “不会抛出错误”。这是一个要求。除非您手动验证字符串不是超出
int范围的数字,否则确保这一点的唯一方法是捕获异常。而 that 正是提出的问题:如何捕获 numberformat 异常。
标签: java numberformatexception