Try, Except & Finally
A try/except block lets your program catch an exception and respond sensibly instead of crashing. It's how real programs survive bad input, missing files and network problems.
The basic try/except
Put the code that might fail inside try. If an exception of the named type happens, Python jumps straight to the matching except block, then carries on after it.
def to_number(text):
try:
return int(text)
except ValueError:
print(f"'{text}' is not a whole number")
return None
print(to_number("42"))
print(to_number("forty"))
The classic use is asking the user for a number until they type a valid one:
while True:
text = input("How old are you? ")
try:
age = int(text)
break # only reached if int() worked
except ValueError:
print("Please type a whole number, e.g. 19.")
print(f"Next year you will be {age + 1}.")
A sample run, where the user first types a word:
Handling different exceptions
You can have several except blocks. Python uses the first one that matches.
prices = {"sugar": 180, "rice": 220}
def total_cost(item, quantity):
try:
return prices[item] * int(quantity)
except KeyError:
print(f"Sorry, we don't sell {item}.")
except ValueError:
print(f"'{quantity}' is not a valid quantity.")
return 0
print(total_cost("rice", "3"))
print(total_cost("bread", "2"))
print(total_cost("sugar", "two"))
To handle several types the same way, list them in a tuple: except (KeyError, ValueError):. To read the error message, add as and a name: except ValueError as error:.
else and finally
A full try statement has up to four parts:
| Block | When it runs |
|---|---|
try | Always runs first |
except | Only if a matching exception happened in try |
else | Only if try finished with no exception |
finally | Always, whether there was an error or not, even after return |
try raises an error that an except block matches, that block runs; if no error is raised, else runs. finally runs in every case, even when an unmatched error carries on up to the caller.def safe_divide(a, b):
try:
result = a / b
except ZeroDivisionError:
print("Cannot divide by zero")
return None
except TypeError as error:
print("Bad types:", error)
return None
else:
print("Division worked")
return result
finally:
print("safe_divide finished")
print(safe_divide(10, 4))
print(safe_divide(5, 0))
print(safe_divide(5, "2"))
Look carefully at the order: finally runs before the function actually hands back its value, which is why "safe_divide finished" appears before each result is printed. Use else for code that should run only on success, which keeps the try block small. Use finally for clean-up that must always happen, such as closing a connection or saving a log.
Catching broadly, carefully
Sometimes, at the very top of a program, you want to catch anything unexpected, log it and exit politely. Use except Exception as error: for that, and keep it as the last except block.
def main():
data = {"total": 1500}
print(data["count"]) # oops: no such key
try:
main()
except Exception as error:
print(f"Something went wrong ({type(error).__name__}: {error})")
A bare except: (with no exception type) catches everything, including typos that cause NameError and even Ctrl+C. Bugs then fail silently and become very hard to find. Always name the exceptions you expect, and use except Exception only as a last resort at the top level.
Putting twenty lines inside one try block makes it unclear which line you expected to fail, and may catch errors you didn't mean to hide. Keep the try block to the one or two lines that can actually raise the exception, and move the rest into else.
Ask forgiveness or look before you leap?
Python programmers often prefer "it's easier to ask forgiveness than permission" (EAFP): just try the operation and handle the exception. The alternative, "look before you leap" (LBYL), checks first.
stock = {"pens": 40, "books": 12}
# LBYL: check first
if "rulers" in stock:
print(stock["rulers"])
else:
print("No rulers recorded")
# EAFP: try, then handle
try:
print(stock["rulers"])
except KeyError:
print("No rulers recorded")
# Often simplest of all for dictionaries
print(stock.get("rulers", 0))
Both styles are valid. EAFP shines when checking first is awkward or unreliable, for example with files, which could be deleted between your check and your open().
When the code that might fail also needs clean-up (like closing a file), a with statement is usually neater than finally. See Context Managers.
Key points
tryruns risky code;except SomeErrorhandles that error.- Use several
exceptblocks, or a tuple, for different exception types. elseruns on success;finallyalways runs, even afterreturn.- Name specific exceptions; avoid bare
except:. - Next, learn to signal your own errors with raise.
Tip: use the ← and → keys to move between pages.
