Reputation: 1
In my exception handling, I'm trying to catch ZeroDivisionError's but for some reason, the code is still doing the division by 0 and not bringing back an error. I must be doing something wrong but I can't seem to place it.
I have tried to move the division elsewhere in the function, and move the division error catch as well.
filename = "numbers.txt"
def main():
total = 0.0
number = 0.0
counter = 0
average = 0
#Open the numbers.txt file
try:
infile = open(filename, 'r')
#Read the values from the file
for line in infile:
counter = counter + 1
number = float(line)
total += number
average = total / counter
#Close the file
infile.close()
except IOError:
print('An error occurred trying to read the file', end=' ')
print(filename, '.', sep='')
except ValueError:
print('Non-numeric data found in the file', end=' ')
print(filename, '.', sep='')
except Exception as err:
print('A general exception occurred.')
print(err)
except ZeroDivisionError:
print('Cannot devide by zero.')
else:
print('Average:', average)
print('Processing Complete. No errors detected.')
# Call the main function.
main()
I'm expecting the result to return the error message when dividing by zero, but it's returning zero as the answer instead.
Upvotes: 0
Views: 12478
Reputation: 57
It seems like there is no ZeroDivisionError in your file. Because in your for loop, you have incremented counter variable by 1 already. Unless, the for loop is iterating into an empty object.
Hence, your average = total / counter will always start as:
average = total / 1 (since counter = counter + 1)
Hope it helped.
Upvotes: 0
Reputation: 1032
You need to change the order that you catch exceptions. Since all exceptions in Python inherit from the Exception base class, you are never getting the ZeroDivision exception since it is caught by handling of Exception. Try this:
except IOError:
print('An error occurred trying to read the file', end=' ')
print(filename, '.', sep='')
except ValueError:
print('Non-numeric data found in the file', end=' ')
print(filename, '.', sep='')
except ZeroDivisionError:
print('Cannot devide by zero.')
except Exception as err:
print('A general exception occurred.')
print(err)
else:
print('Average:', average)
print('Processing Complete. No errors detected.')
Upvotes: 2