Download presentation
Presentation is loading. Please wait.
Published byAustin Lane Modified over 9 years ago
1
Exceptions CMSC 201
2
Overview Exceptions are run-time errors, especially ones that the programmer cannot predict. example 1: division by zero example 2: user enters "garbage" data example 3: disk full
3
Vocabulary When some piece of code causes a run-time error, we say that the code throws an exception or that it raises an exception. The part of a program that deals with the run-time error catches the exception or handles the exception.
4
Divide by Zero totalBill = 67 n = int(input("Number of people? ")) share = totalBill / n print("Share of the bill is ", share) If user enters 0, Python complains and terminates: Traceback (most recent call last): File "divide_by_zero.py", line 3, in share = totalBill / n ZeroDivisionError: division by zero
5
Exception Handling try: totalBill = 67 n = int(input("Number of people? ")) share = totalBill / n except ZeroDivisionError : print("Customers ran away") else: print("Share of the bill is ", share)
6
Syntax for Exceptions try: block of code that might cause one or more types of exceptions except ExceptionType1 : block of code to handle ExceptionType1 except ExceptionType2 : block of code to handle ExceptionType2... else: block of code to execute when no exceptions found
7
Exception Types
10
Badgering the user for input done = False while not done: try: userInput = input("Enter a number: ") n = int(userInput) except ValueError: print("That's not an integer! Try again.") else: print("Thank you!") done = True print("n is ", n)
11
Badgering the user for input
12
done = False while not done: try: userInput = input("Enter a number: ") n = int(userInput) except ValueError: print("That's not an integer! Try again.") except EOFError: print("Please type something! Try again.") else: print("Thank you!") done = True print("n is ", n)
13
Raising an Exception You can write code that raises exceptions: try: raise ZeroDivisionError except ZeroDivisionError: print("Did someone divide by zero?") else: print("Everything is hunky-dory") More useful later when we look at functions
14
BaseException The BaseException type matches all exceptions, even ones you don't know about. Use this very carefully! Might not be a good idea. What can you do if you catch a BaseException? o exit the program slightly more gracefully. o return to home state (if this is possible). o re-throw the exception (requires more syntax and not clear what is accomplished).
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.