Part 06 / Topic 4 of 10
try / except
Put the risky line in try. Put the "what to do if it fails" code in except.
It is like a safety net under a tightrope walker: if they fall, the net catches them and the show goes on.
Always name the specific exception you expect. as e stores the exception in e; print(e) shows its message.
Real-world example: convert the quantity typed in an order form.
text = "two"
try:
qty = int(text)
except ValueError as e:
print("Please type a number.")
print("Details:", e)
qty = 1
print("Quantity:", qty)
Please type a number.
Details: invalid literal for int() with base 10: 'two'
Quantity: 1
Many except blocks
Python checks them top to bottom and runs the first one that matches.
prices = {"tea": 15, "coffee": 25}
def price_per_person(item, people):
try:
return prices[item] / people
except KeyError:
return f"'{item}' is not on the menu"
except ZeroDivisionError:
return "People must be more than 0"
print(price_per_person("tea", 3)) # 5.0
print(price_per_person("juice", 3)) # 'juice' is not on the menu
print(price_per_person("coffee", 0)) # People must be more than 0
You can also catch two types in one block: except (ValueError, TypeError):.
๐ Going deeper: order matters. Put specific exceptions before general ones: if
except LookupError:came first, theKeyErrorblock below it would never run. After anexceptblock ends, Python deletese, so do not use it later.
Read more: the official tutorial's errors and exceptions chapter.
Done here? The practice set for Part 6 โ 7 exercises with solutions โ is on the part page.