Exceptions and try/except
When something goes wrong while a program runs, Python raises an exception. Unhandled, it stops the program with an error message. With try and except, you can catch it and decide what happens instead.
try and except
Python
text = input("Enter a number: ")
try:
number = int(text)
print("Double is", number * 2)
except ValueError:
print(f"'{text}' isn't a whole number.")
print("The program carries on.")Python runs the try block. If a ValueError happens inside it, Python jumps to the except block instead of crashing.
Catch specific exceptions
Name the exceptions you expect, and handle each one appropriately:
Python
def safe_divide(a, b):
try:
return a / b
except ZeroDivisionError:
print("Can't divide by zero.")
except TypeError:
print("Both values must be numbers.")
print(safe_divide(10, 2))
safe_divide(10, 0)
safe_divide(10, "two")Common built-in exceptions
| Exception | Raised when |
|---|---|
ValueError | a value has the right type but a wrong value: int("abc") |
TypeError | an operation gets the wrong type: "a" + 1 |
ZeroDivisionError | dividing by zero |
KeyError | a dictionary key doesn't exist |
IndexError | a list index is out of range |
FileNotFoundError | opening a file that isn't there |
NameError | using a name that doesn't exist |
Getting the error message
as gives you the exception object, whose message you can print or log:
Python
prices = {"tea": 20}
try:
print(prices["coffee"])
except KeyError as error:
print("Missing key:", error)else and finally
elseruns only if no exception happened.finallyruns always, whether there was an error or not. It's the place for clean-up.
Python
def parse_age(text):
try:
age = int(text)
except ValueError:
print(f" {text!r}: not a number")
else:
print(f" {text!r}: age {age}")
finally:
print(" (checked)")
parse_age("42")
parse_age("forty")Keep asking until the input is valid
Python
while True:
try:
n = int(input("Positive number: "))
if n <= 0:
print("It must be positive.")
continue
break
except ValueError:
print("That's not a number.")
print("You chose", n)Finished this lesson?Mark it complete to earn +20 XP and move your progress on.