【发布时间】:2014-04-01 23:02:24
【问题描述】:
我想知道如何在一个字符串变量上设置 try/catch,但必须像这样检查整数:
public static void isValidAge(String age) {
int age2 = Integer.parseInt(age);
try {
if(age2 <= 0 || age2 >= 150) {
throw new NumberFormatException();
}
}
catch (NumberFormatException ex) {
if(age2 <= 0) {
System.err.print("Age can not be 0 or negative.");
}
else if (age2 >= 150) {
System.err.print("Age can not be equal to or more than 150.");
}
else if (age.contains("#@$")) {
System.err.print("You did not enter a valid age.");
}
}
}
try/catch 还必须能够处理字符并保持程序运行。
【问题讨论】:
-
为什么要抛出异常,如果你在同一个块中捕获它?您可以使用简单的 ifs 而不必为整个异常处理而烦恼。在
Integer.parseInt()方法上使用它,它实际上做了一些事情。
标签: java char integer try-catch