Python Try...Except Examples
Short, runnable programs that show python exceptions: try, except, else and finally in action. Read the explanation, press Run, then change the code and try your own ideas. New to the topic? Start with the Python Exceptions: try, except, else and finally lesson.
1Handling several exception types at once
A tuple of exception types catches any of them. type(err).__name__ tells you which one actually happened.
values = ["12", "zero", "0", None]
for v in values:
try:
print(f"100 / {v} =", 100 / int(v))
except (ValueError, TypeError, ZeroDivisionError) as err:
print(f"{v!r} -> {type(err).__name__}: {err}")Expected output100 / 12 = 8.333333333333334
'zero' -> ValueError: invalid literal for int() with base 10: 'zero'
'0' -> ZeroDivisionError: division by zero
None -> TypeError: int() argument must be a string, a bytes-like object or a real number, not 'NoneType'
2finally runs even after return
finally runs whether the function returns normally or an exception escapes, which makes it the safe place for clean-up code.
def load_settings(name):
print("Opening", repr(name))
try:
if name == "":
raise ValueError("file name is empty")
return {"theme": "dark"}
finally:
print("Closing", repr(name))
print(load_settings("app.cfg"))
try:
load_settings("")
except ValueError as err:
print("Error:", err)Expected outputOpening 'app.cfg'
Closing 'app.cfg'
{'theme': 'dark'}
Opening ''
Closing ''
Error: file name is empty
3Asking again until the input is valid
A while True loop with try/except keeps asking until the answer is usable; else: break leaves the loop once it is. The Input box supplies three answers, one per input() call.
while True:
text = input("How many tickets? ")
try:
tickets = int(text)
if tickets < 1:
raise ValueError("you need at least 1 ticket")
except ValueError as err:
print("Try again:", err)
else:
break
print("Booked", tickets, "tickets")Expected outputHow many tickets? abc
Try again: invalid literal for int() with base 10: 'abc'
How many tickets? 0
Try again: you need at least 1 ticket
How many tickets? 3
Booked 3 tickets
4A custom exception for your own rules
A custom exception class gives your error a meaningful name, so callers can catch exactly that problem and nothing else.
class OutOfStockError(Exception):
pass
stock = {"pen": 5, "notebook": 0}
def buy(item, qty):
available = stock.get(item, 0)
if qty > available:
raise OutOfStockError(f"only {available} {item}(s) left")
stock[item] = available - qty
return f"Bought {qty} {item}(s)"
for item, qty in [("pen", 2), ("notebook", 1), ("pen", 4)]:
try:
print(buy(item, qty))
except OutOfStockError as err:
print("Sorry:", err)Expected outputBought 2 pen(s)
Sorry: only 0 notebook(s) left
Sorry: only 3 pen(s) left
Practise next
Python Exceptions: try, except, else and finally exercises → Back to the lesson
Python TypeError: What It Means and How to Fix It examplesPython KeyError: What It Means and How to Fix It examplesPython IndexError: list index out of range examplesPython File Handling examples