Question: Good morning! I am working this morning on a python assignment that is dealing with exception handling. I have written a program that works for

Good morning! I am working this morning on a python assignment that is dealing with exception handling. I have written a program that works for the good data file (numbers.txt in program) but throws a syntax error about non-numeric data(numbersBadData.txt) instead of the exception handler working. The program correctly sums and averages the numbers.txt but the ValueError exception handler wont work! So, I guess my question is how do I fix my program to where the second "try" statment uses the ValueError handler i set up?

PS: In the numbers.txt file, I have 25 two digit numbers. In numbersBadData.txt, I have the same first 24 digits then "xx" to trigger the valueError.

Code:

def main(): try: numbersGood = open('c:/numbers.txt', 'r') except IOError: print("An error occured trying to read the file.") else: total = 0 for line in numbersGood: total = total + int(line)

average = total / 25 print("The total of the values in numbers.txt is: " + str(total)) print("The average of the values in numbers.txt is: " + str(average)) numbersGood.close()

try: numbersBad = open('c:/numbersBadData.txt', 'r')

except ValueError: print("Non-numeric data found in the file.") else: total = 0 for line in numbersBad: total = total + int(line)

average = total / 25 print("The total of the values in numbersBadData.txt is: " + str(total)) print("The average of the values in numbersBadData.txt is: " + str(average)) numbersBad.close()

finally: print("The program is complete.") main()

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!