CMU 15-112: Fundamentals of Programming and Computer Science
Class Notes: Exceptions (Advanced Testing)


 Learning Goal: handle errors/exceptions while running code. In particular:
  1. Basic Exception Handling
  2. Catching Specific Exceptions
  3. Raising an Exception
  4. Check 10.4

  1. Basic Exception Handling
    Sometimes we know that code might throw an error, and we want it to keep running anyway. We can do this by putting the possibly-breakable code into a try block. We follow this with an except block, which clarifies what should happen if an error does occur. This also keeps the code from crashing!
    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. Catching Specific Exceptions
    What if we only want to catch certain types of errors, or if we need to use the exception in some way? We can restrict the except statement to a specific Exception type, and we can store that exception value using as, then use it later.
    def divide(): try: x = int(input("What's the numerator?")) y = int(input("What's the denominator?")) print(x / y) except ValueError: print("That's not a number!") except Exception as e: print("Oh no, you broke something!") print("Error:", type(e)) # Input 4 and 2, and you get 2 # Input 4 and foo, and you get a personalized error message # Input 8 and 0, and you get a general error message divide()

  3. Raising an Exception
    Sometimes, we want to throw a personalized Exception, usually if some kind of bad input is provided. We can do this using a raise statement.
    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!")

  4. Check 10.4