Python exceptions
last modified November 29, 2026 Python 3.15
In this article we show how to work with exceptions in Python.
An exception is an object that signals an error during the execution of a program. When an operation fails, for example a division by zero or a conversion of an invalid string to a number, Python raises an exception. The normal flow of the program stops, and Python looks for code that handles the exception. If there is none, the program ends and prints a traceback.
Exceptions separate the code that detects an error from the code that decides what to do about it. A function deep in a program can raise an exception, and a caller several levels up can handle it.
An unhandled exception
The following program divides by zero. Nothing in the program handles the resulting exception.
total = 120
people = 0
print("splitting the bill")
share = total / people
print(share)
The first print statement runs, then the division raises a
ZeroDivisionError. Python prints a traceback: the file and
line where the error occurred, the failing expression with the operator
marked, and finally the exception type and its message. The last print
statement never runs, and the program exits with a nonzero status.
$ python unhandled.py
splitting the bill
Traceback (most recent call last):
File "/home/user/exceptions/unhandled.py", line 5, in <module>
share = total / people
~~~~~~^~~~~~~~
ZeroDivisionError: division by zero
Catching an exception
Code that can fail is placed in a try block. An
except clause names the exception type it handles. When that
exception is raised in the try block, the rest of the block is
skipped and the handler runs.
total = 120
people = 0
try:
share = total / people
print(share)
except ZeroDivisionError:
print("cannot split the bill among zero people")
print("program continues")
The division raises ZeroDivisionError, so
print(share) is skipped and the handler prints a message.
Because the exception was handled, the program continues normally after
the try statement.
$ python catching.py cannot split the bill among zero people program continues
The exception object
The as clause binds the exception object to a name. The
object carries the error message and other details.
text = "4.5 kg"
try:
weight = float(text)
except ValueError as e:
print("message:", e)
print("type:", type(e).__name__)
print("args:", e.args)
print("e" in dir())
Converting the string to a float raises a ValueError.
Printing the object shows its message, and the args
attribute holds the arguments it was created with. The name bound by
as is deleted when the handler ends, so e does
not exist after the try statement.
$ python exception_object.py
message: could not convert string to float: '4.5 kg'
type: ValueError
args: ("could not convert string to float: '4.5 kg'",)
False
Several exception types
A try statement can have several except clauses.
They are tested in order, and the first one that matches the exception
runs. One clause can also handle several types listed in a tuple.
values = ["12", "abc", "0", "4"]
for v in values:
try:
result = 60 / int(v)
print(f"60 / {v} = {result}")
except ValueError:
print(f"{v!r} is not a number")
except ZeroDivisionError:
print(f"{v!r} is zero")
data = {"width": 40, "label": "box"}
for key in ["width", "label", "height"]:
try:
print(key, data[key] + 2)
except (KeyError, TypeError) as e:
print(key, "failed:", type(e).__name__, e)
In the first loop, int("abc") raises a
ValueError and dividing by int("0") raises a
ZeroDivisionError; each has its own handler. In the second
loop, adding 2 to a string raises a TypeError and a missing
key raises a KeyError. Both are handled by the clause with the
tuple, and type(e).__name__ tells which one occurred.
$ python several_handlers.py 60 / 12 = 5.0 'abc' is not a number '0' is zero 60 / 4 = 15.0 width 42 label failed: TypeError can only concatenate str (not "int") to str height failed: KeyError 'height'
The else and finally clauses
The else clause runs when the try block raised no
exception. The finally clause runs in all cases, whether an
exception occurred or not, and is used for cleanup.
readings = ["21.5", "n/a", "19.0"]
for r in readings:
try:
value = float(r)
except ValueError:
print(f"skipping {r!r}")
else:
print(f"stored {value}")
finally:
print("checked", r)
For the valid readings, the else clause stores the value; for
n/a, the handler runs instead. The finally
clause prints its line for every reading. Keeping only the risky
conversion in the try block ensures that errors in the
else code are not caught by mistake. The
Python try keyword article looks at the
order of these clauses in more detail.
$ python else_finally.py stored 21.5 checked 21.5 skipping 'n/a' checked n/a stored 19.0 checked 19.0
The exception hierarchy
Exception types are classes arranged in a hierarchy. An
except clause matches the named class and all its
subclasses. Related errors share a base class:
IndexError and KeyError are both
LookupErrors, and ZeroDivisionError is an
ArithmeticError.
print(ZeroDivisionError.__mro__)
print(KeyError.__mro__)
colours = ["red", "green"]
stock = {"apples": 4}
for action in ["index", "key", "divide"]:
try:
if action == "index":
print(colours[5])
elif action == "key":
print(stock["pears"])
else:
print(10 / 0)
except LookupError as e:
print("lookup error:", type(e).__name__)
except ArithmeticError as e:
print("arithmetic error:", type(e).__name__)
print(issubclass(KeyboardInterrupt, Exception))
print(issubclass(KeyboardInterrupt, BaseException))
The __mro__ attribute lists a class and its base classes. A
bad list index and a missing dictionary key are both handled by the
LookupError clause. All ordinary exceptions derive from
Exception. KeyboardInterrupt, raised by
Ctrl+C, and SystemExit derive directly from
BaseException, so that except Exception does not
stop the user from interrupting a program. Because the first matching
clause wins, handlers for specific types must come before handlers for
their base classes.
$ python hierarchy.py (<class 'ZeroDivisionError'>, <class 'ArithmeticError'>, <class 'Exception'>, <class 'BaseException'>, <class 'object'>) (<class 'KeyError'>, <class 'LookupError'>, <class 'Exception'>, <class 'BaseException'>, <class 'object'>) lookup error: IndexError lookup error: KeyError arithmetic error: ZeroDivisionError False True
Raising exceptions
The raise statement raises an exception. It is used when a
program detects invalid data that it cannot work with. The argument is an
exception object, usually created with a message.
age_text = "-3"
age = int(age_text)
if age < 0:
raise ValueError(f"age cannot be negative: {age}")
print("age accepted")
The string is a valid integer, so int succeeds, but a
negative age makes no sense. The program raises a ValueError
with a message that includes the bad value. The message appears in the
traceback.
$ python raising.py
Traceback (most recent call last):
File "/home/user/exceptions/raising.py", line 5, in <module>
raise ValueError(f"age cannot be negative: {age}")
ValueError: age cannot be negative: -3
Propagation through functions
An exception that is not handled in a function leaves the function and propagates to its caller, then to the caller's caller, until a handler is found. The traceback shows the whole chain of calls.
def parse_price(text):
return float(text.strip("€ "))
def order_total(prices):
total = 0
for p in prices:
total += parse_price(p)
return total
print(order_total(["€ 12.50", "€ 3.20"]))
try:
print(order_total(["€ 9.90", "free"]))
except ValueError as e:
print("order rejected:", e)
print(order_total(["€ 1.00", "?"]))
parse_price does not handle conversion errors, and neither
does order_total. In the second call, the
ValueError passes through both functions and is handled at the
top level. The third call has no handler, so the traceback lists all three
frames, from the top-level call down to float in
parse_price.
$ python propagation.py
15.7
order rejected: could not convert string to float: 'free'
Traceback (most recent call last):
File "/home/user/exceptions/propagation.py", line 19, in <module>
print(order_total(["€ 1.00", "?"]))
~~~~~~~~~~~^^^^^^^^^^^^^^^^^
File "/home/user/exceptions/propagation.py", line 8, in order_total
total += parse_price(p)
~~~~~~~~~~~^^^
File "/home/user/exceptions/propagation.py", line 2, in parse_price
return float(text.strip("€ "))
~~~~~^^^^^^^^^^^^^^^^^^
ValueError: could not convert string to float: '?'
Re-raising an exception
A handler can do some work, such as reporting the error, and then pass the
exception on. A bare raise statement inside an
except clause raises the current exception again.
import json
documents = ['{"id": 1}', '{"id": 2', '{"id": 3}']
loaded = []
try:
for doc in documents:
try:
loaded.append(json.loads(doc))
except json.JSONDecodeError as e:
print(f"bad document {doc!r}: {e.msg}")
raise
except ValueError:
print("import aborted")
print("loaded:", loaded)
print(issubclass(json.JSONDecodeError, ValueError))
The inner handler prints which document is broken and re-raises the
exception. The outer try statement catches it as a
ValueError, because json.JSONDecodeError is a
subclass of ValueError, and stops the import. The third
document is never parsed.
$ python reraise.py
bad document '{"id": 2': Expecting ',' delimiter
import aborted
loaded: [{'id': 1}]
True
Custom exceptions
A program can define its own exception types by subclassing
Exception. A custom type lets callers catch exactly the errors
of a particular kind, and it can carry extra data as attributes.
class InsufficientFundsError(Exception):
def __init__(self, balance, amount):
super().__init__(f"cannot withdraw {amount}, balance is {balance}")
self.balance = balance
self.amount = amount
def withdraw(balance, amount):
if amount > balance:
raise InsufficientFundsError(balance, amount)
return balance - amount
balance = 100
for amount in [30, 90, 50]:
try:
balance = withdraw(balance, amount)
print("withdrew", amount, "balance", balance)
except InsufficientFundsError as e:
print("error:", e)
print("missing:", e.amount - e.balance)
InsufficientFundsError passes a message to the base class and
stores the balance and the requested amount. The handler prints the message
and uses the attributes to compute the missing sum. After the failed
withdrawal the balance is unchanged, and the next withdrawal succeeds.
Classes are covered in the Python methods
and related OOP articles.
$ python custom_exception.py withdrew 30 balance 70 error: cannot withdraw 90, balance is 70 missing: 20 withdrew 50 balance 20
Exception chaining
When a handler translates a low-level exception into a higher-level one,
the original error should not be lost. raise ... from e links
the new exception to the one that caused it.
class ConfigError(Exception):
pass
settings = {"port": "80a"}
try:
port = int(settings["port"])
except ValueError as e:
raise ConfigError("invalid port in settings") from e
The ConfigError is raised with the ValueError as
its cause. The traceback shows both exceptions, joined by the line
The above exception was the direct cause of the following
exception. The cause is also available in the
__cause__ attribute of the new exception.
$ python chaining.py
Traceback (most recent call last):
File "/home/user/exceptions/chaining.py", line 8, in <module>
port = int(settings["port"])
ValueError: invalid literal for int() with base 10: '80a'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/home/user/exceptions/chaining.py", line 10, in <module>
raise ConfigError("invalid port in settings") from e
ConfigError: invalid port in settings
Errors inside handlers
When an exception occurs while another one is being handled, Python
records the first one as the context of the second. This happens without
any from clause.
stock = {"apples": 4}
try:
print(stock["pears"])
except KeyError:
print(undefined_name)
The handler itself contains a bug: it uses an undefined name. The
traceback shows the original KeyError and then the
NameError, joined by During handling of the above
exception, another exception occurred. This wording tells that the
second error is probably a bug in the handler rather than a deliberate
translation. raise ... from None suppresses the context when
it is not useful.
$ python context.py
Traceback (most recent call last):
File "/home/user/exceptions/context.py", line 4, in <module>
print(stock["pears"])
~~~~~^^^^^^^^^
KeyError: 'pears'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/home/user/exceptions/context.py", line 6, in <module>
print(undefined_name)
^^^^^^^^^^^^^^
NameError: name 'undefined_name' is not defined
Adding notes
The add_note method attaches extra text to an exception. The
notes are printed after the message in the traceback. They are useful for
adding context, such as a file name or a line number, without changing the
exception type.
rows = ["Anna,31", "Boris,x", "Clara,27"]
for line_no, row in enumerate(rows, start=1):
name, age = row.split(",")
try:
age = int(age)
except ValueError as e:
e.add_note(f"in row {line_no}: {row!r}")
raise
print(name, age)
The conversion of x fails in the second row. The handler adds
a note with the row number and content and re-raises the exception. The
traceback shows the original ValueError followed by the note,
which identifies the bad input.
$ python notes.py
Anna 31
Traceback (most recent call last):
File "/home/user/exceptions/notes.py", line 6, in <module>
age = int(age)
ValueError: invalid literal for int() with base 10: 'x'
in row 2: 'Boris,x'
Exception groups
Sometimes several independent errors should be reported together, for
example after validating all inputs or after running several tasks
concurrently. An ExceptionGroup wraps a list of exceptions,
and the except* clause handles the exceptions of a given type
from the group.
errors = []
for text in ["10", "ten", "0", "5"]:
try:
print(100 // int(text))
except (ValueError, ZeroDivisionError) as e:
errors.append(e)
try:
if errors:
raise ExceptionGroup("invalid inputs", errors)
except* ValueError as group:
for e in group.exceptions:
print("not a number:", e)
except* ZeroDivisionError as group:
print("zero divisions:", len(group.exceptions))
The loop collects the exceptions instead of stopping at the first one.
They are raised together in one ExceptionGroup. Each
except* clause receives a group with only the matching
exceptions, so both clauses run: one for the ValueError and
one for the ZeroDivisionError. Exceptions that no clause
matches would be re-raised in a new group.
$ python groups.py 10 20 not a number: invalid literal for int() with base 10: 'ten' zero divisions: 1
Source
Errors and exceptions in the Python tutorial, Built-in exceptions, The try statement, The raise statement
In this article we have read tracebacks, caught exceptions with try and except, used the exception object, the else and finally clauses, and the exception hierarchy, raised and re-raised exceptions, defined a custom exception class, chained exceptions, added notes, and handled exception groups with except*. See also Python try keyword, Python assert, Python with statement, and Python context managers.
Author
List all Python tutorials.