Maybe it's a foolish mistake but I can't understand:
I'm making a method to get the average between some numbers read from a file.
I've already handled the NumberFormatException
in case my file contains non-numeric carachters,
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!");
}
}
and then I tried to handle also the ArithmeticException
in case my file is empty, so that the division should be 0.0/0
try {
average = sum/getNRows();
}
catch(ArithmeticException e) {
System.out.println("Error! File is empty! ArithmeticException!");
}
return average;
//method ends
But when I test my program calling average() on a empty file, it doesn't catch ArithmeticException but outputs "NaN". What should I do in order to catch something displaying me the file is empty, and inform the user it doesn't make sense/it's wrong to call average()?