def kaboom(list, n): print list[n] # trigger IndexError try: kaboom([0, 1, 2], 3) except IndexError: # catch exception here print 'Hello world!' ### MyError = "my error" def stuff(file): raise MyError file = open('data', r) # open a file try: stuff(file) # raises exception finally: file.close() # always close file