【发布时间】:2021-06-13 09:02:43
【问题描述】:
也许这是一个愚蠢的错误,但我无法理解:
我正在制作一种方法来获取从文件中读取的一些数字之间的平均值。
我已经处理了NumberFormatException,以防我的文件包含非数字字符,
double sum = 0.0;
double average = 0.0;
ArrayList<String> list = getCollectionFromFile();
for(String strValue : list) {
try {
double value = Double.parseDouble(strValue);
sum+=value;
}
catch(NumberFormatException e) {
System.out.println("Error! Non-numeric carachters detected!");
}
}
然后我尝试处理ArithmeticException,以防我的文件为空,因此除法应为 0.0/0
try {
average = sum/getNRows();
}
catch(ArithmeticException e) {
System.out.println("Error! File is empty! ArithmeticException!");
}
return average;
//method ends
但是当我在一个空文件上测试调用 average() 的程序时,它不会捕获 ArithmeticException 而是输出“NaN”。 我应该怎么做才能捕捉到显示文件为空的内容,并告知用户它没有意义/调用 average() 是错误的?
【问题讨论】:
-
你确定你试图捕捉的
ArithmeticException被扔进了你的try块吗?在该块之前或之后,您是否还有更多可能引发ArithmeticException的代码?顺便说一句,使用ArithmeticException检查文件是否为空很尴尬。之前检查文件大小,让你的代码看起来更干净,更容易理解。 -
@MarcusFihlon 等等,这不是那么尴尬。我通常知道这样做很奇怪,但这是逻辑:除以零 = 没有行 = 文件为空。有什么奇怪的?不,我没有其他代码可以捕获 ArithmeticException。在编写代码之前检查文件大小的好技巧
-
这里的做法很糟糕。您不应依赖无关的异常来告诉您文件为空。你应该检查
list.size() explicitly。 -
@user207421 所以我可以解决在条件“if(!file.exists())”下将括号括在我的代码中而不会抛出异常,好的,但是如果我想抛出(或直接捕获)一些东西)通知用户它是空的并且不能执行平均计算,我该怎么办?