Table of Contents
IronForgeCyber
Courses
Resources
Blog
Log In


IronForgeCyber

AboutPrivacyTerms

© 2026 IronForgeCyber. All rights reserved.

  1. courses
  2. python
  3. exceptions
10 min read

Exceptions

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.

Reading a Traceback

Here is a small script that parses a list of ports, with one bad value in it:

ports.py
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:

  1. The last line is the exception's type and message: a ValueError, because int() was given 'http'. This alone often tells you what went wrong.
  2. The frame just above it is where the exception happened: line 2, inside parse_port.
  3. Each frame above that is the call that led there: 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.

Handling Exceptions

try and except

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:

python
1def parse_port(text):
2    try:
3        return int(text)
4    except

If 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:

python
1def lookup(table, key):
2    try:
3        return int(table[key
Don't catch everything
A bare except:, 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.

else and finally

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:

python
1def read_config(path):
2    try:
3        f = open(path)
4

For files and other resources, the with statement from File I/O is usually a cleaner way to guarantee cleanup than finally.

Common Exceptions

These are the exceptions you'll run into most, and what usually causes each one:

ExceptionRaised when
ValueErrorA value has the right type but a bad value, such as int("http")
TypeErrorAn operation gets the wrong type, such as "a" + 1 or calling a non-function
KeyErrorA dictionary key doesn't exist
IndexErrorA sequence index is out of range
AttributeErrorAn object doesn't have the attribute or method you asked for, such as None.split
NameErrorA variable name isn't defined, often a typo
FileNotFoundErroropen() was given a path that doesn't exist
ZeroDivisionErrorDividing or taking % by zero
StopIterationnext() was called on an exhausted iterator
RecursionErrorRecursion 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.

Raising Exceptions

Your own code can raise exceptions with raise, followed by an exception object. Pass a message describing the problem:

python
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:

python
1try:
2    port = parse_port(text)
3except ValueError:
4    print(f"skipping bad line: {text

When you catch one exception and raise a different one, raise ... from ... records the original as the cause, and the traceback shows both:

python
1try:
2    port = config["port"]
3except KeyError as e:
4    raise RuntimeError("config is missing a port"

assert

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:

python
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.

Custom Exceptions

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:

python
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.

EAFP versus LBYL

There are two ways to deal with an operation that might fail. LBYL, "look before you leap", checks first:

python
1if key in table:
2    value = table[key]
3else:
4    value = default

EAFP, "easier to ask forgiveness than permission", just tries it and handles the failure:

python
1try:
2    value = table[key]
3except KeyError:
4    value = default

Python 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":

python
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.

load
(
lines
)
:
6 return [parse_port(line) for line in lines]
7
8
9ports = load(["80", "443", "http"])
ValueError
:
5 return None
6
7parse_port("443") # Return: 443
8parse_port("http") # Return: None
]
)
4 except KeyError:
5 print(f"no entry for {key!r}")
6 except (ValueError, TypeError) as e:
7 print(f"bad value for {key!r}: {e}")
8
9lookup({"port": "80"}, "host") # Console: no entry for 'host'
10lookup({"port": "eighty"}, "port") # Console: bad value for 'port': invalid literal for int() with base 10: 'eighty'
except
FileNotFoundError
:
5 print("no config, using defaults")
6 return {}
7 else:
8 data = f.read()
9 f.close()
10 print("loaded", path)
11 return {"raw": data}
12 finally:
13 print("done")
65536
:
4 raise ValueError(f"port out of range: {port}")
5 return port
!r
}
"
)
5 raise
)
from
e
5 parts = line.split()
6 if len(parts) != 3:
7 raise ParseError(f"expected 3 fields, got {len(parts)}: {line!r}")
8 return parts
9
10try:
11 parse_line("10.0.0.5 open")
12except ParseError as e:
13 print(e) # Console: expected 3 fields, got 2: '10.0.0.5 open'
True
5 except ValueError:
6 return False
7
8is_number("-5") # Return: True
9is_number("3.14") # Return: True
10is_number("http") # Return: False