CMU 15-112: Fundamentals of Programming and Computer Science
Class Notes: Exceptions
- 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.") - 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!")