Exceptions
error catching.py
while True: try: x = int(input("Please enter an integer: ")) break except ValueError: print("That was not an integer, try again.")
assertion.py
while True: try: word = input("Enter a word that is 3 letters long: ") assert len(word) == 3 print("Word is 3 letters long, goodbye!") break except AssertionError: print("Word was not 3 letters long!")
os error.py
import sys try: file = open('somefilethatdoesntexist.txt') #catch OS errors: except OSError as error: print("OS Error: " + str(error)) #catch all other errors: except: print("Unexpected error:", sys.exc_info()[0]) #if everything went smoothly: else: print("There were no exceptions.")