Lesson 30 of 34 · Errors & Pythonic Tools
Python Exceptions: try, except, else and finally
Things go wrong in every real program: a user types letters where a number belongs, a file is missing, a list turns out to be empty. Python reports such problems by raising an exception. If nothing handles it, the program stops with a traceback — but with try and except you can catch the exception and recover gracefully.
Reading a traceback
age = int("twelve")
Traceback (most recent call last):
File "main.py", line 1, in <module>
age = int("twelve")
ValueError: invalid literal for int() with base 10: 'twelve'
Read tracebacks from the bottom up: the last line names the exception type (ValueError) and explains what happened; the lines above show where.
Common built-in exceptions
| Exception | Typical cause |
|---|---|
ValueError |
right type, wrong value: int("abc") |
TypeError |
wrong type: "a" + 1 |
KeyError |
missing dictionary key |
IndexError |
list index out of range |
ZeroDivisionError |
dividing by zero |
AttributeError |
missing attribute or method: None.upper() |
FileNotFoundError |
opening a file that doesn't exist |
try and except
Put the code that might fail in a try block and the recovery code in an except block:
text = "twelve"
try:
age = int(text)
except ValueError:
age = 0
print(age) # 0
If the try block succeeds, the except block is skipped. If a ValueError occurs, Python jumps straight to except — the rest of the try block never runs.
Catch specific exceptions
Name the exceptions you expect, use several except clauses for different reactions, and add as to access the exception object:
def lookup(prices, item, count):
try:
return prices[item] / count
except KeyError:
return f"{item} is not for sale"
except ZeroDivisionError as error:
return f"Bad count: {error}"
print(lookup({"rope": 6}, "rope", 0)) # Bad count: division by zero
A tuple catches several types with one clause: except (ValueError, TypeError):. Catching everything with except Exception: is occasionally right — at the top level of a program, or in a function whose whole job is to report failures — but in ordinary code it hides real bugs.
else and finally
A try statement can have two more blocks:
elseruns only if thetryblock raised no exception — the place for code that should run on success but whose own errors you don't want to catch.finallyruns no matter what — success, handled exception, unhandled exception, even after areturn. It's used for cleanup such as closing files or releasing locks.
def divide(a, b):
try:
result = a / b
except ZeroDivisionError:
print("Cannot divide by zero")
return None
else:
print("Division worked")
return result
finally:
print("Finished")
divide(6, 3) # Division worked, Finished -> returns 2.0
divide(6, 0) # Cannot divide by zero, Finished -> returns None
Ask forgiveness, not permission
Python developers often prefer to just try an operation and handle the failure (EAFP: "easier to ask forgiveness than permission") rather than check every condition in advance (LBYL: "look before you leap"). try: value = d[key] except KeyError: ... is as Pythonic as if key in d:. Choose whichever reads more clearly.
Common mistakes
- A bare
except:catches everything, including typos in your own code and the user pressing Ctrl+C. Always name the exception. - Silencing errors with
except ValueError: passmakes bugs invisible. At least log or report what happened. - Too much code in
try: keep only the line that can fail inside, so you don't accidentally catch errors from unrelated code. - Wrong order of
exceptclauses: Python uses the first matching clause, soexcept Exceptionbeforeexcept ValueErrormeans the second never runs.
Assignment
Write three functions:
safe_divide(a, b)returnsa / b, orNonewhenbis zero. CatchZeroDivisionError— don't checkbwith anif.parse_int(text, default=0)returnsint(text), ordefaultwhen the text isn't a valid whole number (ValueError).run_safely(func, log)callsfunc()with no arguments and records what happens by appending strings to the listlog:- append
"start"before callingfunc; - if
funcraises anyException, append"error: <ExceptionTypeName>"and returnNone; - otherwise append
"success"(in anelseblock) and returnfunc's result; - in every case, append
"done"last (in afinallyblock).
- append
safe_divide(10, 4) # 2.5
parse_int("abc", default=-1) # -1
log = []
run_safely(lambda: 1 / 0, log) # None
log # ["start", "error: ZeroDivisionError", "done"]Premium lesson
Unlock the full Learn Python course
- All 34 lessons, bosses and quizzes — lifetime access
- One payment of $35, no subscription
- Finish within 30 days and claim $10.50 (30%) back
Want more than one course?
The All-Access Pass unlocks all 8 courses and every new one we release, for $120 once.
Errors and exceptions in other languages
- JavaScript Error Handling: try, catch and Custom Errors · JavaScript
- Go Error Handling: error Values and if err != nil · Go
- Java Exceptions: try, catch, finally and Custom Exceptions · Java
- C# Exceptions: try, catch, finally and Custom Exceptions · C#
Need a quick reminder? The Python cheat sheet has every topic of Learn Python on one page.
Lesson last updated on .