Exception Handling in Python
Published by Brayan K
Learn to detect, catch, and manage errors gracefully so your programs never crash unexpectedly.
Part of the free Python course at LearnCodingFast — hands-on lessons with examples you run in your browser, plus practice exercises and a quick quiz.
An error stops the program, unless you handle it
Every lesson so far has shown errors stopping a program at the line that failed, and Introduction to Python showed how to read the report, from the bottom up. Python calls these errors exceptions:
print("Before")
age = int("abc")
print("After")
# ✅ Expected output:
# Before
# ✅ Expected error:
# ValueError: invalid literal for int() with base 10: 'abc'try and except let the program handle an exception instead of stopping. This lesson is about what goes wrong when people use them.
When a line in try fails, the rest of the try is skipped
Python runs the lines under try. If one fails with the error an except names, Python jumps to that except straight away, and carries on after it:
for text in ["41", "abc"]:
try:
age = int(text)
print("Next year you will be", age + 1)
except ValueError:
print("Not a whole number:", text)
print("Carrying on")
# ✅ Expected output:
# Next year you will be 42
# Not a whole number: abc
# Carrying onThe failed line never finished, so the name it would have set never got a value. Code after the try that uses it fails instead:
text = "abc"
try:
age = int(text)
except ValueError:
print("Not a whole number:", text)
print("Next year you will be", age + 1)
# ✅ Expected output:
# Not a whole number: abc
# ✅ Expected error:
# NameError: name 'age' is not definedCode that should run only when the try worked goes in else, which runs when the try raised nothing:
for text in ["41", "abc"]:
try:
age = int(text)
except ValueError:
print("Not a whole number:", text)
else:
print("Next year you will be", age + 1)
# ✅ Expected output:
# Next year you will be 42
# Not a whole number: abcA bare except: hides your own mistakes
An except: with no error named catches everything, including bugs you never meant to catch. Here a name left over from an earlier version of the function looks like "not a number":
def to_number(text):
try:
return int(raw_text)
except:
return 0
print(to_number("42"))
print(to_number("abc"))
# ✅ Expected output:
# 0
# 0The function never works, and nothing says why. Name the error you expect, and the real bug shows up:
def to_number(text):
try:
return int(raw_text)
except ValueError:
return 0
print(to_number("42"))
# ✅ Expected error:
# NameError: name 'raw_text' is not definedexcept Exception would hide that NameError too. Errors come in families, and issubclass() asks whether one kind of error is a kind of another. Nearly every error is an Exception. Three that aren't are Ctrl+C, KeyboardInterrupt; a program asking to stop, SystemExit; and GeneratorExit, which Python raises inside a generator to close it. A bare except: catches them as well:
print(issubclass(ValueError, Exception))
print(issubclass(NameError, Exception))
print(issubclass(KeyboardInterrupt, Exception))
print(issubclass(SystemExit, Exception))
print(issubclass(GeneratorExit, Exception))
# ✅ Expected output:
# True
# True
# False
# False
# FalseAnd an except only catches what it names; anything else still stops the program:
try:
total = int("12") + int("x")
except TypeError:
print("Caught it")
# ✅ Expected error:
# ValueError: invalid literal for int() with base 10: 'x'e is the error, not just its message
except KeyError as e puts the error itself in e. Printing it shows its message, and type(e).__name__ its kind. A KeyError's message is the missing key, in quotes:
stock = {"apple": 3}
try:
print(stock["pear"])
except KeyError as e:
print("Missing:", e)
print("Type:", type(e).__name__)
# ✅ Expected output:
# Missing: 'pear'
# Type: KeyErrortry:
int("12a")
except ValueError as e:
print("Could not convert:", e)
print(f"In an f-string: {e}")
# ✅ Expected output:
# Could not convert: invalid literal for int() with base 10: '12a'
# In an f-string: invalid literal for int() with base 10: '12a'But e isn't a string, so joining it to one with + raises a new error inside the except:
try:
int("12a")
except ValueError as e:
print("Could not convert: " + e)
# ✅ Expected error:
# TypeError: can only concatenate str (not "ValueError") to strOn your own computer, the report for this shows the ValueError first, then "During handling of the above exception, another exception occurred:", then the TypeError. And the name after as is deleted when the except block ends:
try:
int("12a")
except ValueError as err:
print("Caught:", err)
print(err)
# ✅ Expected output:
# Caught: invalid literal for int() with base 10: '12a'
# ✅ Expected error:
# NameError: name 'err' is not definedTo use the message later, copy it into another name inside the block:
try:
int("12a")
except ValueError as err:
problem = str(err)
print("Saved:", problem)
# ✅ Expected output:
# Saved: invalid literal for int() with base 10: '12a'Python takes the first except that matches
Python tries the except clauses from the top and runs the first one that matches. A broad one first hides the specific one below it, and Python gives no warning:
text = "abc"
try:
number = int(text)
except Exception:
print("Something went wrong")
except ValueError:
print("Not a whole number:", text)
# ✅ Expected output:
# Something went wrongor doesn't list two errors: ValueError or TypeError is just ValueError, by the rule from Operators and Expressions, so the TypeError gets through:
for value in ["7", None]:
try:
print(int(value) * 2)
except ValueError or TypeError:
print("Can't double", repr(value))
# ✅ Expected output:
# 14
# ✅ Expected error:
# TypeError: int() argument must be a string, a bytes-like object or a real number, not 'NoneType'A tuple of errors catches each of them:
for value in ["7", "x", None]:
try:
print(int(value) * 2)
except (ValueError, TypeError) as e:
print("Can't double", repr(value), "-", type(e).__name__)
# ✅ Expected output:
# 14
# Can't double 'x' - ValueError
# Can't double None - TypeErrorA family's name catches all its members. KeyError and IndexError are both LookupErrors, and type(e).__name__ says which one it was:
data = {"names": ["Ada", "Ben"]}
for key, index in [("names", 0), ("names", 5), ("ages", 0)]:
try:
print(data[key][index])
except LookupError as e:
print(type(e).__name__, e)
# ✅ Expected output:
# Ada
# IndexError list index out of range
# KeyError 'ages'A few more families: dividing by zero is an ArithmeticError, a missing file is an OSError, and the JSON error from Working with JSON is a ValueError:
import json
print(issubclass(KeyError, LookupError), issubclass(IndexError, LookupError))
print(issubclass(ZeroDivisionError, ArithmeticError))
print(issubclass(FileNotFoundError, OSError))
print(issubclass(json.JSONDecodeError, ValueError))
# ✅ Expected output:
# True True
# True
# True
# TrueTwo mistakes Python refuses before anything runs: a bare except: above another one is SyntaxError: default 'except:' must be last, and before Python 3.14, except ValueError, TypeError: without brackets is a SyntaxError too.
else and finally aren't the same as code after the try
else runs only when the try raised nothing; finally runs every time, even when the function is returning. This function says which part runs for three calls:
def divide(a, b):
try:
result = a / b
except ZeroDivisionError as e:
print(" except :", e)
return None
except TypeError as e:
print(" except :", e)
return None
else:
print(" else : result is", result)
return result
finally:
print(" finally: runs every time")
for a, b in [(10, 2), (10, 0), (10, "x")]:
print("divide", repr(a), repr(b))
print("returned", divide(a, b))
# ✅ Expected output:
# divide 10 2
# else : result is 5.0
# finally: runs every time
# returned 5.0
# divide 10 0
# except : division by zero
# finally: runs every time
# returned None
# divide 10 'x'
# except : unsupported operand type(s) for /: 'int' and 'str'
# finally: runs every time
# returned Nonefinally runs even when no except catches the error; the error carries on after it:
def load(text):
try:
return int(text)
finally:
print("Finished with", repr(text))
print(load("5"))
print(load("five"))
# ✅ Expected output:
# Finished with '5'
# 5
# Finished with 'five'
# ✅ Expected error:
# ValueError: invalid literal for int() with base 10: 'five'The except clauses guard only the try. An error in else isn't caught by them, which is the point of else: the except covers only the line you meant it to:
rows = ["7", "x"]
try:
first = int(rows[0])
except ValueError:
print("The first row is not a number")
else:
second = int(rows[1])
print(first + second)
# ✅ Expected error:
# ValueError: invalid literal for int() with base 10: 'x'For files, a with block from File Handling already does the cleaning up a finally would: it closes the file even when an error stops the block, and what was written before the error is saved:
from pathlib import Path
try:
with open("log.txt", "w", encoding="utf-8") as f:
f.write("started\n")
f.write(10)
except TypeError as e:
print("Caught:", e)
print("Closed:", f.closed)
print(repr(Path("log.txt").read_text(encoding="utf-8")))
# ✅ Expected output:
# Caught: write() argument must be str, not int
# Closed: True
# 'started\n'raise: how a function refuses
Functions said a function that meets a problem it can't handle can raise an error for its caller to deal with. An error inside a function reaches the caller anyway:
def average(marks):
return sum(marks) / len(marks)
try:
print(average([]))
except ZeroDivisionError as e:
print("The caller caught:", e)
# ✅ Expected output:
# The caller caught: division by zero"division by zero" doesn't tell the caller what was wrong. raise stops the function with an error of your choosing and a message that says what happened:
def average(marks):
if not marks:
raise ValueError("average() needs at least one mark")
return sum(marks) / len(marks)
for marks in [[70, 80], []]:
try:
print(average(marks))
except ValueError as e:
print("Skipped:", e)
# ✅ Expected output:
# 75.0
# Skipped: average() needs at least one markPick the built-in error that fits: ValueError for a value of the right type that can't be used, TypeError for a value of the wrong type. A function can also check its arguments and refuse before doing anything:
def withdraw(balance, amount):
if amount > balance:
raise ValueError(f"cannot take {amount} from {balance}")
return balance - amount
print(withdraw(50, 20))
try:
print(withdraw(50, 80))
except ValueError as e:
print("Refused:", e)
# ✅ Expected output:
# 30
# Refused: cannot take 80 from 50Inside an except, raise on its own raises the same error again, after you've done something about it, such as printing what went wrong:
def parse_score(text):
try:
return int(text)
except ValueError:
print("Bad score:", repr(text))
raise
parse_score("12a")
# ✅ Expected output:
# Bad score: '12a'
# ✅ Expected error:
# ValueError: invalid literal for int() with base 10: '12a'raise needs an error, not a string: raise "Something broke" stops with TypeError: exceptions must derive from BaseException, and a bare raise outside an except with RuntimeError: No active exception to reraise. You can also make your own kinds of error, which takes a class: Custom Exceptions & Exception Chaining shows how, after Object-Oriented Programming.
Sometimes trying beats checking first
String Methods showed that isdigit() can't promise that int() will work. To find out whether text is a whole number, try the conversion:
def to_int(text):
try:
return int(text)
except ValueError:
return None
for text in ["42", " 42", "-5", "²", "3.5"]:
print(repr(text), text.isdigit(), to_int(text))
# ✅ Expected output:
# '42' True 42
# ' 42' False 42
# '-5' False -5
# '²' True None
# '3.5' False Noneint() reads spaces and a minus sign, which isdigit() rejects, and isdigit() accepts ², which int() can't read. A file that may not be there is the same kind of question. Modern File Paths with pathlib checked first; catching FileNotFoundError also covers a file that disappears between the check and the read. Its full message includes platform-dependent paths and error numbers. The example checks which filename failed, then prints the reason and supplies an empty fallback:
from pathlib import Path
notes = Path("practice") / "notes.txt"
try:
text = notes.read_text(encoding="utf-8")
except FileNotFoundError as e:
print("Requested file missing:", e.filename == str(notes))
print("Reason:", e.strerror)
text = ""
print(len(text), "characters")
# ✅ Expected output:
# Requested file missing: True
# Reason: No such file or directory
# 0 charactersNot every question needs a try: for a dictionary key that may be missing, get() from Dictionaries is shorter.
Errors from modules
Modules raise errors of their own. Regular Expressions (re) raises re.error for a pattern it can't read:
import re
for pattern in ["[0-9]+", "[0-9"]:
try:
print(pattern, re.findall(pattern, "room 101, floor 3"))
except re.error as e:
print(pattern, "is not a valid pattern:", e)
# ✅ Expected output:
# [0-9]+ ['101', '3']
# [0-9 is not a valid pattern: unterminated character set at position 0From Python 3.13 the error is called re.PatternError, and re.error is another name for it, so except re.error works on every version. On 3.12 and earlier, and in this site's editor, re.PatternError doesn't exist. Working with JSON's json.loads() raises json.JSONDecodeError:
import json
for text in ['{"name": "Ada"}', "{'name': 'Ada'}"]:
try:
data = json.loads(text)
except json.JSONDecodeError as e:
print("Not JSON:", e)
else:
print("Name:", data["name"])
# ✅ Expected output:
# Name: Ada
# Not JSON: Expecting property name enclosed in double quotes: line 1 column 2 (char 1)And the requests package from HTTP Requests & APIs raises errors that are all kinds of requests.RequestException: a failed connection, a timeout, and the HTTPError that raise_for_status() raises. It needs the network, so this one is code without output:
import requests
try:
resp = requests.get("https://api.github.com/users/octocat", timeout=10)
resp.raise_for_status()
except requests.RequestException as e:
print("Request failed:", e)
else:
user = resp.json()
print(user["login"])Practice: adding up prices
parse_price() should refuse a negative price, and the loop should skip anything that isn't a price and add up the rest. The blanks are the word that refuses, the error to catch, and the part that runs only for a price that worked; the hints at the end name them.
def parse_price(text):
price_value = float(text)
if price_value < 0:
___ ValueError(f"negative price: {price_value}")
return price_value
total = 0
for text in ["2.50", "abc", "-1", "4"]:
try:
price_value = parse_price(text)
except ___ as e:
print("Skipped", repr(text), "-", e)
___:
total += price_value
print("Total:", total)
# 👉 replace ___ with raise
# 👉 replace ___ with ValueError
# 👉 replace ___ with else
# ✅ Expected output:
# Skipped 'abc' - could not convert string to float: 'abc'
# Skipped '-1' - negative price: -1.0
# Total: 6.5On your own: a fruit order
Work out each order's cost from the price list. Report a fruit that isn't on the list and a quantity that isn't a whole number, each in its own words, and print the total of the orders that worked.
prices = {"apple": 0.5, "pear": 0.75}
orders = [("apple", "3"), ("pear", "2"), ("kiwi", "1"), ("apple", "lots")]
# your code hereprices = {"apple": 0.5, "pear": 0.75}
orders = [("apple", "3"), ("pear", "2"), ("kiwi", "1"), ("apple", "lots")]
total = 0
for fruit, qty_text in orders:
try:
cost = prices[fruit] * int(qty_text)
except KeyError:
print(f"{fruit}: not on the price list")
except ValueError as e:
print(f"{fruit}: bad quantity ({e})")
else:
total += cost
print(f"{fruit} x{qty_text} = {cost}")
print("Total:", total)
# ✅ Expected output:
# apple x3 = 1.5
# pear x2 = 1.5
# kiwi: not on the price list
# apple: bad quantity (invalid literal for int() with base 10: 'lots')
# Total: 3.0
Practice quiz
try: print("A"), then int("x"), then print("B"); except ValueError: print("C"); then, after the try, print("D"). What prints?
- A, C, D
- A, B, C, D
- C, D
- A, then it stops with ValueError
Answer: A, C, D. When int("x") fails, the rest of the try is skipped, the except runs, and the program carries on after the try.
prices = {"tea": 2}. try: prices["coffee"]; except KeyError as e: print(e). What prints?
- coffee
- 'coffee'
- KeyError: 'coffee'
- Key not found
Answer: 'coffee'. A KeyError's message is the missing key, shown with its quotes.
Around int("x"): except Exception: print("general"), then except ValueError: print("specific"). What prints?
- specific
- general, then specific
- general
- It stops with a SyntaxError
Answer: general. Python runs the first except that matches, and ValueError is a kind of Exception, so the second clause is never reached.
Around int(None): except ValueError or TypeError: print("caught"). What happens?
- It prints caught
- Nothing; it finishes
- It stops with a SyntaxError
- It stops with TypeError: int() argument must be a string, a bytes-like object or a real number, not 'NoneType'
Answer: It stops with TypeError: int() argument must be a string, a bytes-like object or a real number, not 'NoneType'. ValueError or TypeError is just ValueError, so the TypeError isn't caught. Catch both with a tuple: (ValueError, TypeError).
try: a = int("1"); except ValueError: print("caught"); else: b = int("x"). What happens?
- It prints caught
- It stops with ValueError: invalid literal for int() with base 10: 'x'
- Nothing; it finishes
- It stops with a SyntaxError
Answer: It stops with ValueError: invalid literal for int() with base 10: 'x'. The except clauses only cover the try. An error in else isn't caught by them.
def f(): try: return "try" finally: print("finally"). Then print(f()). What prints?
- try
- finally
- finally, then try
- try, then finally
Answer: finally, then try. finally runs as the function leaves, before print() gets the returned value.
try: int("x"); except ValueError as e: pass. Then, after the try: print(e). What happens?
- It stops with NameError: name 'e' is not defined
- invalid literal for int() with base 10: 'x'
- None
- ValueError
Answer: It stops with NameError: name 'e' is not defined. The name after as is deleted when the except block ends. Copy what you need into another name inside the block.
Inside except ValueError as e: print("Error: " + e). What happens?
- Error: invalid literal for int() with base 10: 'x'
- Error: ValueError
- It stops with a SyntaxError
- It stops with TypeError: can only concatenate str (not "ValueError") to str
Answer: It stops with TypeError: can only concatenate str (not "ValueError") to str. e is the exception object, not text. Use a comma, an f-string or str(e).
Continue this course
- Previous: File Handling
- Next: Modules and Packages — Organise code into reusable files and import the Python standard library
- Quick reference: Python cheat sheet › Exceptions
- From the blog: 10 Python Tips Every Beginner Should Know · Error Handling Best Practices in Python
Frequently asked questions
Should my code check the text of an error message?
No: check the type of error, or its attributes, such as filename on a FileNotFoundError. Python's documentation says messages aren't part of its API and may change between versions, and they do: max() of an empty list words its error differently from Python 3.12, and the error for a bad regular expression is called re.PatternError from 3.13.
How do I print the whole traceback and keep going?
Call traceback.print_exc() inside the except block (after import traceback): it prints the report Python would have printed, and the program carries on. Logging, Debugging & Error Handling at Scale shows the logging module's way to record errors.
How do I ignore one error on purpose?
Catch it and do nothing, with pass in the except block, and name the error you mean, so others still stop the program. For a file you're deleting, pathlib's unlink(missing_ok=True) does that in one call.