CMU 15-110: Principles of Computing
Exceptions


# For 110, we just need to know the basics of try/except. # When an error occurs in a "try", control transfers to the "except" body. def demoTryExcept(): totalValues = 0 exceptions = 0 while True: try: print() print('Values entered:', totalValues) print('Exceptions: ', exceptions) response = input("Enter an integer (try 0, or 'ack', 'q' to quit): ") if (response == 'q'): print('Good bye!') return totalValues += 1 d = int(response) # this could fail, if response is not an int print(' 2 /', d, '= ', 2/d) # this could fail, if d is 0 except: print(' Yikes, something bad just happened') exceptions += 1 demoTryExcept()