When the program crashes, catch the error first: Python exception handling
An exception is not a broken program: it is Python telling you what went wrong, with a name you can catch. Following Chapter 8 of the official Python Tutorial: syntax errors vs exceptions, try/except, matching by inheritance, which errors to catch and which to leave alone, raise, else, finally, with, user-defined exceptions, chaining, and ExceptionGroup — plus a 100-accident breakdown from a fictional bookstore script.

First, the boundaries of this guide. This is the fourth guide in the "Python Basics" series, continuing from the first three: the first covered variables, types, and control flow, the second covered functions and modules, and the third covered classes and inheritance. This one covers exception handling: when a program crashes, how to catch the error, how to stop it yourself, and how to make sure the cleanup always runs. Classes and exceptions are two independent skills, but they meet at one point: the custom exceptions at the end of this guide are themselves written with classes — which is why the classes guide was not wasted effort. The example is still the fictional "Morning Light Bookstore": a small neighborhood bookstore whose bookkeeping script can already work out stock, give discounts, and manage books with classes. The new problem in this guide is that a running script keeps meeting surprises — the owner types a wrong number, the file to read does not exist, someone tries to sell more copies than are in stock — and until now each surprise has crashed the whole program and left nothing behind. Every statement about exceptions comes from Chapter 8, "Errors and Exceptions", of the official Python Tutorial; sources are listed in each guide's meta information and evidence record. Every operation, code sample, and number built around the Morning Light Bookstore was made up to explain how things work; none of it is a real record. By the end of this guide you should be able to do four things: tell syntax errors apart from exceptions and read the last line of an error message; write try/except to catch a named error and know in what order several except clauses match; use raise to raise an error yourself, and use else and finally to separate "only runs if nothing went wrong" from "runs no matter what"; and give the bookstore's own errors their own exception names, and know when to use with for cleanup.
Step 1: Two kinds of errors — a syntax error is written wrong, an exception goes wrong while running
Chapter 8 of the official tutorial starts by distinguishing two kinds of errors: syntax errors and exceptions. Syntax errors, also known as parsing errors, are perhaps the most common kind of complaint you get while you are still learning Python: the program has not run yet, and the parser already refuses. The tutorial's example is a missing colon:
>>> while True print('Hello world')
File "<stdin>", line 1
while True print('Hello world')
^^^^^
SyntaxError: invalid syntax
The parser repeats the offending line and displays little arrows pointing at the place where the error was detected. Note that this is not always the place that needs to be fixed: in this example the error is detected at print, since a colon is missing just before it. The file name and line number are printed so you know where to look.
Exceptions are different: the statement itself is written correctly, but something goes wrong when it runs. The tutorial gives three at once:
>>> 10 * (1/0)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
10 * (1/0)
~^~
ZeroDivisionError: division by zero
>>> 4 + spam*3
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
4 + spam*3
^^^^
NameError: name 'spam' is not defined
>>> '2' + 2
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
'2' + 2
~~~~^~~
TypeError: can only concatenate str (not "int") to str
Each error has its own name: ZeroDivisionError is division by zero, NameError is using a name that was never defined, and TypeError is adding a string and an integer directly. The last line of the error message indicates what happened, and the lines above it are the "traceback", listing the call stack where the error occurred. My judgment is: when you are new, reading the last line of an error message is enough — it tells you the type of the error and the reason straight away. The traceback is a map for tracing "which line did this start on", and the longer the program, the more you will need it. Remember this: an exception does not mean "the program is broken"; it is Python telling you "something went wrong here" in a way that has a name. A name means it can be caught — and that is what this guide is about.
Step 2: try/except — catch it first, then talk
Section 8.3 of the tutorial offers a way to write programs that handle selected exceptions. The tutorial's example asks the user for input until a valid integer has been entered, but allows the user to interrupt the program (using Control-C, which is signalled by raising the KeyboardInterrupt exception):
>>> while True:
... try:
... x = int(input("Please enter a number: "))
... break
... except ValueError:
... print("Oops! That was no valid number. Try again...")
...
The tutorial lists how the try statement works in four points: first, the try clause is executed; if no exception occurs, the except clause is skipped and execution of the try statement is finished; if an exception occurs during execution of the try clause, the rest of the clause is skipped, and if its type matches the exception named after the except keyword, the except clause is executed, and then execution continues after the try/except block; if an exception occurs which does not match the exception named in the except clause, it is passed on to outer try statements, and if no handler is found, it is an unhandled exception and execution stops with an error message.
The bookstore version: the owner types a price in the terminal, and a typo should not crash the whole script — it should print a hint and ask again. So nobody has to sit and type, the example below uses a list to pretend to be the things the owner typed one after another:
def parse_price(text):
"""Turn a typed price into a number; return None if it cannot be converted."""
try:
return float(text)
except ValueError:
return None
>>> parse_price('59.0')
59.0
>>> parse_price('fifty-nine')
>>> parse_price('39.5')
39.5
parse_price('fifty-nine') prints nothing, because it returns None. A try statement may have more than one except clause, to specify handlers for different exceptions — but at most one handler will be executed. The tutorial also notes: handlers only handle exceptions that occur in the corresponding try clause, not in other handlers of the same try statement. Several exceptions can be caught together by naming them in a tuple:
try:
n = int(text)
total = 100 / n
except (ValueError, ZeroDivisionError):
total = None
Text that is not a number, or a zero, both leave total as None. My judgment is: put only the few lines that can raise this one kind of error inside try — do not stuff the whole function in there. The more you stuff in, the harder it is to tell which line raised the error when one does. That rule ranks third in the chart in step ten.
Step 3: Exceptions have relatives too — except matches by inheritance
A class in an except clause matches exceptions which are instances of the class itself or one of its derived classes — but not the other way around: an except clause listing a derived class does not match instances of its base classes. The tutorial explains this cleanly with three exception classes:
class B(Exception):
pass
class C(B):
pass
class D(C):
pass
for cls in [B, C, D]:
try:
raise cls()
except D:
print("D")
except C:
print("C")
except B:
print("B")
This code prints B, C, D in that order. The tutorial adds: if the except clauses were reversed, with except B first, it would have printed B, B, B — the first matching except clause is triggered. B is the elder of C and D, so written first it catches all of its descendants and the later clauses never get a turn. So the rule is: specific exceptions first, broad ones last. It is the same idea as the inheritance lookup in the third guide: the more specific match wins.
When an exception occurs, it may have associated values, also known as the exception's arguments. The except clause may specify a variable after the exception name, and the variable is bound to the exception instance, which typically has an args attribute that stores the arguments. The tutorial's example:
>>> try:
... raise Exception('spam', 'eggs')
... except Exception as inst:
... print(type(inst)) # the exception type
... print(inst.args) # arguments stored in .args
... print(inst) # __str__ allows args to be printed directly
... x, y = inst.args # unpack args
... print('x =', x)
... print('y =', y)
...
<class 'Exception'>
('spam', 'eggs')
('spam', 'eggs')
x = spam
y = eggs
Built-in exception types define __str__() to print all the arguments without explicitly accessing .args. The bookstore version: when stock runs short while selling, the exception carries the title, the wanted count, and the actual stock, so whoever handles it can see at a glance how many are missing — step nine writes that example. My judgment is: get into the habit of writing except Xxx as err. Leaving off as err throws away the reason for the error; the error message is there for the handling code and for whoever reads the books later, not for decoration.
Step 4: Which errors to catch, and which to leave alone
Not every exception should be caught. Section 8.3 of the tutorial lays out the family tree: BaseException is the common base class of all exceptions; one of its subclasses, Exception, is the base class of all the non-fatal exceptions; exceptions which are not subclasses of Exception are not typically handled, because they are used to indicate that the program should terminate. They include SystemExit, which is raised by sys.exit(), and KeyboardInterrupt, which is raised when a user wishes to interrupt.
That is where a bare except and an except Exception part ways. except Exception can be used as a wildcard that catches almost everything non-fatal — but it does not catch KeyboardInterrupt or SystemExit, so the user can still stop the program with Control-C. A bare except: with no exception name catches everything, including the interrupt, and then the program cannot be stopped at all. The tutorial's advice is: it is good practice to be as specific as possible with the types of exceptions that we intend to handle, and to allow any unexpected exceptions to propagate on. My judgment is: treat that sentence as the central idea of this guide. Catching exceptions is not about "making the program never crash"; it is about "giving expected errors an expected handling, and letting unexpected errors travel upward to be seen".
The tutorial gives the most common pattern for handling Exception: print or log the exception and then re-raise it, allowing a caller to handle the exception as well:
import sys
try:
f = open('myfile.txt')
s = f.readline()
i = int(s.strip())
except OSError as err:
print("OS error:", err)
except ValueError:
print("Could not convert data to an integer.")
except Exception as err:
print(f"Unexpected {err=}, {type(err)=}")
raise
A file that will not open is an OSError, content that will not convert to an integer is a ValueError, and anything else is first written down and then thrown again with a bare raise. Note the last raise has nothing after it — it re-raises the exception currently being handled, so someone higher up the call chain can catch it again. The bookstore version: when reading the restock file and the file is missing, print "restock file not found"; when one line in it is not a number, print which line is not a number; anything else, write it down first and throw it again — never swallow it quietly.
One more point about exception handling that is easy to miss: handlers do not handle only exceptions that occur immediately in the try clause, but also those that occur inside functions that are called, even indirectly, in the try clause. The tutorial's example:
>>> def this_fails():
... x = 1/0
...
>>> try:
... this_fails()
... except ZeroDivisionError as err:
... print('Handling run-time error:', err)
...
Handling run-time error: division by zero
The 1/0 is written inside this_fails, but the error is caught by the try outside it. Exceptions "bubble up": if no layer catches one, it rises all the way to the outermost layer and the program stops. That is also why "only put the lines that can go wrong inside try" matters — the more you put in, the harder the source of the bubble is to find.
Step 5: raise — stopping it yourself
Sometimes you do not wait for an error to happen: the program itself notices that something is wrong and forces a specified exception to occur. Section 8.4 of the tutorial: the raise statement allows the programmer to force a specified exception to occur. The tutorial's example:
>>> raise NameError('HiThere')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
raise NameError('HiThere')
NameError: HiThere
The sole argument to raise indicates the exception to be raised. This must be either an exception instance or an exception class — a class that derives from BaseException, such as Exception or one of its subclasses. If an exception class is passed, it will be implicitly instantiated by calling its constructor with no arguments: raise ValueError is shorthand for raise ValueError().
The bookstore version: before selling, check the stock, and if there is not enough, stop it yourself instead of discovering later that the stock has gone negative:
def check_stock(stock, wanted):
"""Raise an error when stock is short; do not wait for the books to go wrong."""
if wanted > stock:
raise ValueError(f"wanted {wanted} copies, only {stock} in stock")
return stock - wanted
>>> check_stock(7, 2)
5
>>> check_stock(7, 99)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
check_stock(7, 99)
File "<stdin>", line 4, in check_stock
ValueError: wanted 99 copies, only 7 in stock
7 in stock, sell 2, 5 left; ask for 99 with only 7 in stock and a ValueError is raised, with the reason written in the exception's message. In the third guide, sell() used a different shape: "return False if there is not enough". Both shapes have their uses: returning False hands the decision to the caller, and if the caller forgets to check the return value, the error slips past quietly; raising an exception says "this cannot just pass", and the caller must handle it or the program stops. My judgment is: use raise for things the caller "must know", and a return value for things the caller "can decide about". Selling more than the stock allows would corrupt the books, so it belongs to the first kind.
There is one more form of raise, with no argument: if you need to determine whether an exception was raised but do not intend to handle it, a simpler form of the raise statement allows you to re-raise the exception:
>>> try:
... raise NameError('HiThere')
... except NameError:
... print('An exception flew by!')
... raise
...
An exception flew by!
Traceback (most recent call last):
File "<stdin>", line 2, in <module>
raise NameError('HiThere')
NameError: HiThere
First print "an exception flew by", then throw the same exception onward unchanged. The "write it down, then throw it again" pattern from step four uses exactly this spelling.
Step 6: else — code that only runs when nothing went wrong
The try...except statement has an optional else clause, which, when present, must follow all except clauses: it is useful for code that must be executed if the try clause does not raise an exception. The tutorial's example opens several files and counts their lines:
for arg in sys.argv[1:]:
try:
f = open(arg, 'r')
except OSError:
print('cannot open', arg)
else:
print(arg, 'has', len(f.readlines()), 'lines')
f.close()
A file that will not open gets a "cannot open"; one that opens gets its lines counted and is closed. The tutorial adds one key sentence: the use of the else clause is better than adding additional code to the try clause because it avoids accidentally catching an exception that was not raised by the code being protected by the try...except statement. Take a bookstore example: if converting the price to a number were placed inside try, a ValueError from the conversion would be handled as if it were a "file will not open" problem — one error on top of another. Placed in else, a conversion error cannot be wrongly caught by the file layer's except:
def read_first_price(path):
"""Read the price on the first line of a restock file: a missing file
reports a file problem, text that is not a number reports a number problem."""
try:
f = open(path, 'r')
except OSError:
return 'file cannot be opened'
else:
with f:
text = f.readline().strip()
try:
return float(text)
except ValueError:
return 'not a number'
The with f: here is the spelling step eight will explain — look at its shape for now. My judgment is: else is the clause of the try statement most often skipped, but it solves a real problem — "what to do after success" and "what might go wrong" have to be written separately. When writing a try, first ask: is this code "something that might go wrong", or "something that should not run if something went wrong"? The first goes in try, the second in else.
Step 7: finally — cleanup that runs no matter what
The try statement has another optional clause which is intended to define clean-up actions that must be executed under all circumstances. The tutorial's example:
>>> try:
... raise KeyboardInterrupt
... finally:
... print('Goodbye, world!')
...
Goodbye, world!
Traceback (most recent call last):
File "<stdin>", line 2, in <module>
raise KeyboardInterrupt
KeyboardInterrupt
Nobody catches the KeyboardInterrupt, but the "Goodbye, world!" in finally still prints first, and the exception only continues upward afterwards. The tutorial lists the rules in detail: if an exception occurs during execution of the try clause, the exception may be handled by an except clause; if the exception is not handled by an except clause, the exception is re-raised after the finally clause has been executed. An exception could occur during execution of an except or else clause; again, the exception is re-raised after the finally clause has been executed. If the finally clause executes a break, continue, or return statement, exceptions are not re-raised — this can be confusing and is therefore discouraged, and from version 3.14 the compiler emits a SyntaxWarning for it. If the try statement reaches a break, continue, or return statement, the finally clause will execute just prior to that statement's execution.
The tutorial also gives two examples that make you stop and think. The first is bool_return():
>>> def bool_return():
... try:
... return True
... finally:
... return False
...
>>> bool_return()
False
The try wants to return True, the finally returns False — and the answer is False: if a finally clause includes a return statement, the returned value will be the one from the finally clause's return statement, not the value from the try clause's return statement. The second is the tutorial's divide example, which uses except, else, and finally together:
>>> def divide(x, y):
... try:
... result = x / y
... except ZeroDivisionError:
... print("division by zero!")
... else:
... print("result is", result)
... finally:
... print("executing finally clause")
...
>>> divide(2, 1)
result is 2.0
executing finally clause
>>> divide(2, 0)
division by zero!
executing finally clause
>>> divide("2", "1")
executing finally clause
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
divide("2", "1")
File "<stdin>", line 3, in divide
result = x / y
TypeError: unsupported operand type(s) for /: 'str' and 'str'
2 divided by 1 is 2.0, else prints the result, finally runs as usual; 2 divided by 0, except prints "division by zero!", finally runs as usual; two strings divided, except only catches ZeroDivisionError and cannot catch TypeError, so finally runs first and the exception is re-raised afterwards. My judgment is: finally does exactly one job — cleanup. Closing a file, closing a connection, taking down an "in progress" sign: anything that has to happen whether the work succeeded or failed belongs in finally. Do not put business logic in finally, and never put a return in finally: the tutorial says plainly that it is discouraged, and from version 3.14 the compiler warns about it.
Step 8: with — cleanup that comes built in
Some objects define standard clean-up actions to be undertaken when the object is no longer needed, regardless of whether or not the operation using the object succeeded or failed. The tutorial's example reads a file:
for line in open("myfile.txt"):
print(line, end="")
The problem with this code is that it leaves the file open for an indeterminate amount of time after this part of the code has finished executing. That is no issue in simple scripts, but can be a problem for larger applications. The with statement allows objects like files to be used in a way that ensures they are always cleaned up promptly and correctly:
with open("myfile.txt") as f:
for line in f:
print(line, end="")
After the statement is executed, the file f is always closed, even if a problem was encountered while processing the lines. In the tutorial's words: objects which, like files, provide predefined clean-up actions will indicate this in their documentation. The bookstore version: reading a restock file and writing a daily report both go through with open(...) as f, and the file is always closed — no hand-written finally needed to close it. My judgment is: with is "a finally that comes built in", but it only handles cleanup, not catching errors. A line in the file that will not convert to a number still needs its own try for ValueError, inside or outside the with. Cleanup and catching errors are two different jobs; do not expect one with to cover both.
Step 9: User-defined exceptions — giving the bookstore's errors their own names
Programs may name their own exceptions by creating a new exception class. Section 8.6 of the tutorial says exceptions should typically be derived from the Exception class, either directly or indirectly; exception classes can do anything any other class can do, but are usually kept simple, often only offering a number of attributes that allow information about the error to be extracted by handlers. Most exceptions are defined with names that end in "Error", similar to the naming of the standard exceptions.
The bookstore version: running out of stock is a "business error", not one of Python's built-in kinds, and it deserves its own name:
class OutOfStockError(Exception):
"""Not enough stock: the wanted count is more than the stock on hand."""
def __init__(self, title, wanted, stock):
super().__init__(f"{title}: wanted {wanted} copies, only {stock} in stock")
self.title = title
self.wanted = wanted
self.stock = stock
def sell_book(title, stock, wanted):
"""Sell books: return the remaining stock if there is enough,
otherwise raise OutOfStockError."""
if wanted > stock:
raise OutOfStockError(title, wanted, stock)
return stock - wanted
>>> sell_book('The Three-Body Problem', 7, 2)
5
>>> try:
... sell_book('The Three-Body Problem', 7, 99)
... except OutOfStockError as err:
... print(err)
... print(err.title, err.wanted, err.stock)
...
The Three-Body Problem: wanted 99 copies, only 7 in stock
The Three-Body Problem 99 7
7 in stock, sell 2, 5 left; ask for 99 and an OutOfStockError is raised, its message reading "The Three-Body Problem: wanted 99 copies, only 7 in stock", and the exception object itself carries title, wanted, and stock as attributes for the handler to take whichever it needs. Because OutOfStockError derives from Exception, an except Exception can catch it too; the other way round, if a custom exception did not derive from Exception — say it derived directly from BaseException — an except Exception could not catch it. That is one kind of mistake in the chart in step ten.
Naming has its own conventions too: exception class names ending in "Error" are the norm, and OutOfStockError reads as an exception at a glance in a way OutOfStock does not. My judgment is: do not define a custom exception for everything. A file that will not open and a number that will not convert are already covered well enough by Python's own OSError and ValueError. A new name is only worth it when "this error belongs to your business alone, and the caller needs to handle it specially". The bookstore's "out of stock" is exactly such an error: the caller has to decide from it whether to report a shortage or order more stock, which is a completely different matter from "a number that will not convert".
Step 10: When errors pile onto errors — exception chaining, notes, and ExceptionGroup, plus a chart of mistakes
Three advanced tools from the tutorial to finish, one sentence each — enough to know they exist. The first is exception chaining: if an unhandled exception occurs inside an except section, it will have the exception being handled attached to it and included in the error message. The tutorial's example fails to open a database file, then raises a RuntimeError:
>>> try:
... open("database.sqlite")
... except OSError:
... raise RuntimeError("unable to handle error")
...
Traceback (most recent call last):
File "<stdin>", line 2, in <module>
open("database.sqlite")
FileNotFoundError: [Errno 2] No such file or directory: 'database.sqlite'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "<stdin>", line 4, in <module>
raise RuntimeError("unable to handle error")
RuntimeError: unable to handle error
To indicate that an exception is a direct consequence of another, the raise statement allows an optional from clause: raise RuntimeError('Failed to open database') from exc, and the error message will read "The above exception was the direct cause of the following exception". To disable automatic chaining, use the from None idiom. My judgment is: writing from when you convert one exception into another is a good habit. Without it, whoever reads the error sees two exceptions and has to guess whether they are related; with from, the relationship is written in the error message.
The second is add_note: when an exception is created in order to be raised, it is usually initialized with information that describes the error, but there are cases where it is useful to add information after the exception was caught. The tutorial's example:
>>> try:
... raise TypeError('bad type')
... except Exception as e:
... e.add_note('Add some information')
... e.add_note('Add some more information')
... raise
...
Traceback (most recent call last):
File "<stdin>", line 2, in <module>
raise TypeError('bad type')
TypeError: bad type
Add some information
Add some more information
Both notes appear after the exception, in the order they were added. The third is ExceptionGroup: it wraps a list of exception instances so they can be raised together, for situations where it is necessary to report several exceptions that occurred — the tutorial's example raises a group of an OSError and a SystemError:
>>> def f():
... excs = [OSError('error 1'), SystemError('error 2')]
... raise ExceptionGroup('there were problems', excs)
...
>>> try:
... f()
... except Exception as e:
... print(f'caught {type(e)}: {e}')
...
caught <class 'ExceptionGroup'>: there were problems (2 sub-exceptions)
By using except* instead of except, you can selectively handle only the exceptions in the group that match a certain type: except* OSError takes only the OSErrors out of the group and lets the rest propagate. The bookstore script does not need exception groups — it sells one book at a time. But when processing a restock file in bulk, with several bad lines in one batch, collecting them and reporting them together is far more useful than stopping at the first bad line.
Finally, the mistake chart for this guide. Example: the fictional Morning Light Bookstore bookkeeping script in its fourth month of learning Python, 100 exception-handling mistakes, broken down by cause. The top mistake in the chart is the bare except that catches everything without naming an exception — it even blocks the user pressing Control-C to stop the program.

Looking back over the ten steps, this guide really only taught three things. First, errors come in two kinds: a syntax error is written wrong and is stopped before the program runs; an exception goes wrong while running, has a name, and can be caught — and when reading an error message, start with the last line. Second, catching errors takes judgment: write the type specifically, put specific ones first and broad ones last; catch the ones that should be caught and let the ones that should not be caught — like KeyboardInterrupt — travel on; write the error down and re-raise it instead of swallowing it quietly. Third, cleanup is guaranteed: what only runs when nothing went wrong goes in else, what runs no matter what goes in finally, and what brings its own cleanup goes in with; an error unique to your business deserves its own exception name. The next guide is left for file reading and writing: a restock list and a daily report cannot live only in memory — and when that guide comes, the try/except/finally and with from this one will be back, because reading and writing files is where exceptions happen most often.
Comments (0)
Sources
Related articles
A class bundles data and its rules together: one Book class gives every book its own state, methods let objects do the work themselves, and inheritance lets an e-book stand on a paper book's shoulders. Following Chapter 9 of the official Python Tutorial: class and __init__, self, methods, class vs instance variables, attribute lookup, inheritance and overriding, super(), the underscore-private convention, dataclasses, __iter__ and __next__ — plus a 100-accident chart.
A function packs repeated work into a name; a module packs definitions into a file you take out with import. Following Chapter 4 sections 4.8-4.9 and Chapter 6 of the official Python Tutorial: def and return, local and global scope, defaults evaluated once, keyword arguments, *args and **kwargs, / and *, lambda, docstrings and annotations, the ways to import, the __main__ guard, packages and the search path — plus a 100-accident breakdown from a fictional bookstore script.
Variables are boxes for things, lists and dicts are boxes for lots of things, and if, for, and while let a program decide and repeat work on its own. Following Chapters 3-5 of the official Python Tutorial: division and the float quirk, string indexing and slicing, list assignment that never copies, dict get vs KeyError, truthiness, if/elif/else, for and range, while with break/continue/loop-else — plus a 100-accident breakdown from a fictional bookstore script.