【发布时间】:2013-01-10 07:00:29
【问题描述】:
我想以更具体的方式处理 NumberFormatException。 当它尝试分配除整数以外的任何内容时,当输入以下内容时会发生此异常:
- 字符串
- 字符
- 空输入
- 双数
根据输入的内容,我想显示正确的消息,例如
你输入的是字符串,请输入一个整数
或
值不能为空,请输入整数值
下面的代码以一般方式捕获NumberFormatException。
我想知道有没有办法包含更多的 catch 子句。
import java.util.Scanner;
public class TestException {
static int input;
static Scanner scan = new Scanner(System.in);
public static void main(String[] args) {
System.out.println("Enter an integer number: ");
try {
input = Integer.parseInt(scan.next());
System.out.println("You've entered number: " + input);
} catch (NumberFormatException e) {
System.out.println("You've entered non-integer number");
System.out.println("This caused " + e);
}
}
}
【问题讨论】:
-
只显示类似的行“您输入了空白或非数字值。请再试一次”??更好吧?
-
可以在catch子句中分析给定的输入,显然没有内置逻辑来判断字符串作为数字无效的各种任意原因
-
也用错误代码终止进程。 System.exit(1);
-
这可能有点矫枉过正,但您可以使用正则表达式来查看它们是数字还是字母或两者的组合的模式。
标签: java exception-handling validation numberformatexception