When something goes wrong while a program runs, Python raises an exception: an object describing the error. The exception travels back up through the functions that were called to get there, and if nothing along the way handles it, the program stops and prints a traceback. You've already seen a few: IndexError for a list index out of range, KeyError for a missing dictionary key, TypeError for adding a string to a number.
This lesson covers reading tracebacks, handling exceptions on purpose, and raising your own.
Here is a small script that parses a list of ports, with one bad value in it:
1def parse_port(text):
2 return int(text)
3
4
5def Running it crashes with this traceback:
Traceback (most recent call last):
File "ports.py", line 9, in <module>
ports = load(["80", "443", "http"])
^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "ports.py", line 6, in load
return [parse_port(line) for line in lines]
^^^^^^^^^^^^^^^^
File "ports.py", line 2, in parse_port
return int(text)
^^^^^^^^^
ValueError: invalid literal for int() with base 10: 'http'Read a traceback from the bottom up:
ValueError, because int() was given 'http'. This alone often tells you what went wrong.parse_port.parse_port was called by load on line 6, which was called from the top level of the script, shown as <module>, on line 9.The ^^^^ markers, added in Python 3.11, underline the exact expression on each line. The traceback is a record of the call stack at the moment of the crash, so the question to answer is usually "where did the bad value come from?", which means following the frames upward.
To handle an exception, put the code that might raise it in a try block, and the code that deals with the problem in an except block naming the exception type:
1def parse_port(text):
2 try:
3 return int(text)
4 exceptIf the try block raises a ValueError, Python jumps straight to the except block and carries on from there. If it raises nothing, the except block is skipped.
Adding as binds the exception object to a name, so you can inspect or print it. One try can have several except blocks, checked in order, and one except can catch several types listed in a tuple:
1def lookup(table, key):
2 try:
3 return int(table[keyexcept:, or except Exception:, catches every error, including the ones you didn't expect: a typo that raises NameError, or a bug that raises TypeError. The program carries on with bad data and fails somewhere far away, or not at all. Catch the specific exceptions you know how to handle, and let everything else crash with a traceback that tells you what's wrong.A try statement can have two more clauses. else runs only if the try block raised no exception, which keeps the try block itself as small as possible. finally always runs last, whether an exception was raised, handled or not, so it's used for cleanup that has to happen regardless:
1def read_config(path):
2 try:
3 f = open(path)
4For files and other resources, the with statement from File I/O is usually a cleaner way to guarantee cleanup than finally.
These are the exceptions you'll run into most, and what usually causes each one:
| Exception | Raised when |
|---|---|
ValueError | A value has the right type but a bad value, such as int("http") |
TypeError | An operation gets the wrong type, such as "a" + 1 or calling a non-function |
KeyError | A dictionary key doesn't exist |
IndexError | A sequence index is out of range |
AttributeError | An object doesn't have the attribute or method you asked for, such as None.split |
NameError | A variable name isn't defined, often a typo |
FileNotFoundError | open() was given a path that doesn't exist |
ZeroDivisionError | Dividing or taking % by zero |
StopIteration | next() was called on an exhausted iterator |
RecursionError | Recursion went too deep, usually a missing base case |
AttributeError: 'NoneType' object has no attribute ... deserves a special mention. It almost always means a function returned None when you expected a value, such as re.search() finding no match, and the next line tried to use the result.
Your own code can raise exceptions with raise, followed by an exception object. Pass a message describing the problem:
1def parse_port(text):
2 port = int(text)
3 if not 0 < port <Raising is how a function reports that it can't do what was asked. The caller decides whether to handle it, which is better than returning a special value like -1 that the caller might forget to check.
Inside an except block, a bare raise re-raises the exception being handled. Use it to react to an error, such as logging it, without hiding it:
1try:
2 port = parse_port(text)
3except ValueError:
4 print(f"skipping bad line: {textWhen you catch one exception and raise a different one, raise ... from ... records the original as the cause, and the traceback shows both:
1try:
2 port = config["port"]
3except KeyError as e:
4 raise RuntimeError("config is missing a port"An assert statement raises an AssertionError if its condition is false. Use it to check things that should always be true if your code is correct, and to catch your own mistakes early:
assert len(grid) == len(grid[0]), "grid should be square"Asserts are for catching bugs, not for checking user input: running Python with the -O flag removes them entirely. Pytest is built on plain assert statements.
When none of the built-in exceptions fits, define your own by subclassing Exception. The class body can be empty; the new name is what matters, because it gives callers something specific to catch:
1class ParseError(Exception):
2 pass
3
4def parse_line(line):Exceptions are classes, arranged in a hierarchy, and an except clause catches the named class and all of its subclasses. except LookupError catches both KeyError and IndexError, because both inherit from it. The top of the hierarchy looks like this:
BaseException
├── KeyboardInterrupt
├── SystemExit
└── Exception
├── ValueError
├── TypeError
├── LookupError
│ ├── KeyError
│ └── IndexError
├── OSError
│ └── FileNotFoundError
└── ...Your exceptions should inherit from Exception, never directly from BaseException. KeyboardInterrupt, raised when you press Ctrl+C, and SystemExit, raised by sys.exit(), sit outside Exception on purpose, so that except Exception doesn't stop you from interrupting or exiting a program.
There are two ways to deal with an operation that might fail. LBYL, "look before you leap", checks first:
1if key in table:
2 value = table[key]
3else:
4 value = defaultEAFP, "easier to ask forgiveness than permission", just tries it and handles the failure:
1try:
2 value = table[key]
3except KeyError:
4 value = defaultPython code leans toward EAFP. It avoids checking the same thing twice, and it's the only safe option when the situation can change between the check and the action, such as a file being deleted after you checked that it exists. It's also the reliable way to ask questions that are hard to check in advance, like "is this string a valid number?", which isdigit() gets wrong for "-5":
1def is_number(text):
2 try:
3 float(text)
4 return LBYL is still the right call when the check is cheap and failure is common, and many APIs make it unnecessary anyway: table.get(key, default) does the dictionary lookup above in one line.