【发布时间】:2020-01-10 03:15:36
【问题描述】:
当变量 d1 和 d2 的数据类型不正确时,我总是收到默认的 NumberFormatException 消息。
我想在使用 throw 语句条件捕获这些异常时打印我的自定义异常消息。
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter a numeric value: ");
String input1 = sc.nextLine();
Double d1 = Double.parseDouble(input1);
System.out.print("Enter a numeric value: ");
String input2 = sc.nextLine();
Double d2 = Double.parseDouble(input2);
System.out.print("Choose an operation (+ - * /): ");
String input3 = sc.nextLine();
try {
if (!(d1 instanceof Double)) {
throw (new Exception("Number formatting exception caused by: "+d1));
}
if (!(d2 instanceof Double)) {
throw (new NumberFormatException("Number formatting exception caused by: "+d2));
}
switch (input3) {
case "+":
Double result = d1 + d2;
System.out.println("The answer is " + result);
break;
case "-":
Double result1 = d1 - d2;
System.out.println("The answer is " + result1);
break;
case "*":
Double result2 = d1 * d2;
System.out.println("The answer is " + result2);
break;
case "/":
Double result3 = d1 / d2;
System.out.println("The answer is " + result3);
break;
default:
System.out.println("Unrecognized Operation!");
break;
}
}
catch (Exception e){
System.out.println(e.getMessage());
}
}
}
这是输入值格式不正确时打印的消息示例。
输入一个数值:$ 线程“main”java.lang.NumberFormatException 中的异常:对于输入字符串:“$” 在 java.base/jdk.internal.math.FloatingDecimal.readJavaFormatString(FloatingDecimal.java:2054) 在 java.base/jdk.internal.math.FloatingDecimal.parseDouble(FloatingDecimal.java:110) 在 java.base/java.lang.Double.parseDouble(Double.java:543) 在 com.example.java.Main.main(Main.java:13)
【问题讨论】:
-
这是因为,正如堆栈跟踪所指出的,错误发生在
parseDouble中,在您输入不是数字的内容后立即发生。执行甚至都不会“将东西放入d1”,代码抛出,因此在分配发生之前退出main()。 -
如果
String参数无法解析为Double,则对Double#parseDouble(String)的调用将抛出NumberFormatException。这些调用发生在您尝试抛出自己的异常之前。此外,d1和d2将始终是Double的实例,因为它们声明的类型是Double并且它们不能是null——你永远不会将它们设置为null和parseDouble永远不会返回 @987654337 @(该方法实际上返回原始类型double)。