CMU 15-112: Fundamentals of Programming and Computer Science
Class Notes: Exceptions

Note: you are only responsible for the simple use of try/except as demonstrated below. You may optionally see these notes (in Python2) for more details.

  1. Basic Exception Handling (try/except)
    print("This is a demonstration of the basics of try/except.") try: print("Here we are just before the error!") print("1/0 equals:", (1/0)) print("This line will never run!") except: print("*** We just caught an error. ***") print("And that concludes our demonstration.")

  2. Raising an Exception
    def lastChar(s): if (len(s) == 0): # This is (a simple form of) how you raise your own custom exception: raise Exception('String must be non-empty!') else: return s[-1] print(lastChar('abc')) print(lastChar('')) print("This line will never run!")