# errors.py ''' Some ways to handle errors. ''' # Let's first create some errors in our code. # Errors are not detected by python, but are produced during run time. a = 5/0. b = 3+spam c = '2' + 2 # Here we have created three different errors: # ZeroDivisionError, NameError and TypeError # Handle errors: a = 5.4 a = '5.4' try: b = int(a) except ValueError: print("Not a valid number") # One can use more than one except clause: a = 0 try: b = int(a) c = 1/a except ValueError: print("Not a valid number") except ZeroDivisionError: print("Division by zero") except (RuntimeError, TypeError, NameError): pass # Explicitely rise the error. a = 0 try: b = 1/a except: raise raise(ZeroDivisionError) # raise NameError("MyOwnPrivateError") # Clean up using the finally clause. # finally is always executed. def divide(x, y): try: result = x / y except ZeroDivisionError: print("division by zero!") else: print("result is", result) finally: print("executing finally clause")