PYTHON · PYTHON FOR EVERYONE · CHAPTER 10

Exceptions

Keep your scripts running when a device doesn't respond, a file is missing or a broken JSON arrives.

7 min readCourse: Python for EveryoneLevel: beginner

From point A to point B

Point A: your scripts work as long as everything goes well. But a device that doesn't respond, a missing file or a malformed JSON stops them. And you don't know how to read the error message yet. Point B: by the end of this chapter, you'll read a traceback, catch the errors you expect and raise your own. And you'll decide what to do in each case without losing information.

What an exception is and how to read a traceback

An exception is an error that Python detects while it runs the program. It happens in abnormal situations: dividing by 0, opening a file that doesn't exist or converting text that isn't a number into a number. Python "raises" the exception to warn you that something went wrong.

If nobody catches it, the program stops and shows the error information. This script calculates a link's utilization and fails because the capacity is 0:

def utilization(traffic_mbps, capacity_mbps):
    return traffic_mbps / capacity_mbps * 100

def report():
    utilization(850, 0)

report()
$ python3.14 example.py
Traceback (most recent call last):
  File "/path/to/example.py", line 7, in <module>
    report()
    ~~~~~~^^
  File "/path/to/example.py", line 5, in report
    utilization(850, 0)
    ~~~~~~~~~~~^^^^^^^^
  File "/path/to/example.py", line 2, in utilization
    return traffic_mbps / capacity_mbps * 100
           ~~~~~~~~~~~~~^~~~~~~~~~~~~~~
ZeroDivisionError: division by zero

First comes the traceback, or stack trace: the chain of calls that led to the error, from oldest to most recent. Here, line 7 called report(), which on line 5 called utilization(850, 0), which failed on line 2. The ~ and ^ marks point to the exact operation that failed.

The last line is the most important one: the exception's type, ZeroDivisionError, and its description. Always read a traceback from the bottom up.

Catching with try and except

To handle an exception, you use try and except. The try block holds the code that might fail; the except block holds what you want to do if it fails. Sometimes a clear message is enough, other times you should log the error and, occasionally, you can fix the problem.

try:
    with open("running-config.txt", encoding="utf-8") as f:
        text = f.read()
except FileNotFoundError:
    print("The configuration file doesn't exist")
# → The configuration file doesn't exist

Always state the type you expect. A bare except: catches anything, even a typo in your code or the Ctrl+C you press to stop the script. That's how real errors get hidden.

A single try accepts several except clauses, one per error type. Python checks them in order and runs the first one that matches. If none matches, the exception keeps going up to whoever called the function.

def read_vlan(text):
    try:
        vlan = int(text)
        print(description)          # a name that doesn't exist
    except NameError:
        print("The variable doesn't exist")
    except ValueError:
        print(f"{text!r} isn't a VLAN number")

read_vlan("1O")   # → '1O' isn't a VLAN number
read_vlan("10")   # → The variable doesn't exist

With "1O" (with the letter O), int() fails and execution jumps to except ValueError; the print line never runs. With "10", the conversion works and the error comes later, with the nonexistent name.

Python 3.14 update. The book opened the file with file("archivo.txt") and caught IOError. In Python 3, file() doesn't exist: use open() with encoding and with, which closes the file. IOError and EnvironmentError are now aliases of OSError, and there are more precise subclasses, such as FileNotFoundError or PermissionError.

Several error types in one block

If several errors get the same treatment, group them in a tuple. With as, you get the exception object, which holds the message:

def read_vlan(text):
    try:
        vlan = int(text)
        print(description)
    except (NameError, ValueError) as error:
        print(f"An error occurred: {type(error).__name__}: {error}")

read_vlan("1O")
# → An error occurred: ValueError: invalid literal for int() with base 10: '1O'
read_vlan("10")
# → An error occurred: NameError: name 'description' is not defined

Python 3.14 lets you drop the parentheses when you don't use as (PEP 758):

def read_vlan(text):
    try:
        return int(text)
    except ValueError, TypeError:
        return None

print(read_vlan("20"))      # → 20
print(read_vlan("twenty"))  # → None
print(read_vlan(None))      # → None

If you add as, the parentheses are still required. except ValueError, TypeError as e: produces SyntaxError: multiple exception types must be parenthesized when using 'as'. This parenthesis-free syntax doesn't work in versions before 3.14; if your code must run on them, keep the tuple.

Python 3.14 update. The book wrote except MyError, e: to get the exception object. In Python 3, you write except MyError as e:. Be careful when you migrate: in 3.14, the old line no longer raises a syntax error, because it now means "catch MyError or the type stored in e". When the exception occurs, Python looks up the variable e and fails with NameError. In the same way, raise E, "message" became raise E("message").

else and finally

A try can have two more clauses:

  • else runs only if the try finished without exceptions. It separates the code that might fail from the code that depends on its success.
  • finally always runs, whether there's an exception or not. It's the place for cleanup tasks, such as closing an SSH session.
def utilization(traffic, capacity):
    try:
        usage = traffic / capacity * 100
    except ZeroDivisionError:
        print("Capacity can't be 0")
    else:
        print(f"Utilization: {usage:.1f} %")
    finally:
        print("Calculation finished")

utilization(850, 1000)
# → Utilization: 85.0 %
# → Calculation finished
utilization(850, 0)
# → Capacity can't be 0
# → Calculation finished

Don't use return, break or continue to leave a finally. If you do, the exception in progress is silently discarded. Since Python 3.14, the compiler warns you about it (PEP 765):

def connect():
    try:
        raise ConnectionError("timeout")
    finally:
        return "ok"

print(connect())   # → ok  (the ConnectionError vanished)
$ python3.14 finally_return.py
/path/to/finally_return.py:5: SyntaxWarning: 'return' in a 'finally' block
  return "ok"
ok

Raising exceptions and creating your own

You can raise exceptions yourself with raise. And you can define your own: all it takes is a class that inherits from Exception or one of its subclasses. Creating a base class for your project lets you catch all its errors at once.

class NetworkError(Exception):
    """Base class for this program's errors."""

class InvalidVlan(NetworkError):
    def __init__(self, vlan):
        super().__init__(f"VLAN {vlan} outside the 1-4094 range")
        self.vlan = vlan

def configure_vlan(vlan):
    if not 1 <= vlan <= 4094:
        raise InvalidVlan(vlan)
    return f"vlan {vlan}"

for v in (20, 5000):
    try:
        print(configure_vlan(v))
    except InvalidVlan as e:
        print("Error:", e)
        print("Value received:", e.vlan)
# → vlan 20
# → Error: VLAN 5000 outside the 1-4094 range
# → Value received: 5000

Because you pass the message to super().__init__, print(e) shows it without you having to write a __str__ method. The vlan attribute keeps the data for whoever catches the error.

Sometimes you catch a technical error and want to raise a clearer one without losing the original. That's what raise ... from ... is for:

import json

def load(text):
    try:
        return json.loads(text)
    except json.JSONDecodeError as e:
        raise ValueError("The API returned invalid JSON") from e

try:
    load('{"hostname": "R1",}')
except ValueError as e:
    print(e)                            # → The API returned invalid JSON
    print(type(e.__cause__).__name__)   # → JSONDecodeError

If nobody catches the ValueError, the traceback shows both errors. They're linked by the sentence The above exception was the direct cause of the following exception. Inside an except, a bare raise re-raises the current exception as is.

Exception notes and groups

Since Python 3.11, you can add context to an exception with add_note() before re-raising it (PEP 678). The note appears at the end of the traceback:

try:
    int("4O96")
except ValueError as e:
    e.add_note("While reading the VLAN of interface Gi0/3")
    raise
Traceback (most recent call last):
  File "/path/to/note.py", line 2, in <module>
    int("4O96")
    ~~~^^^^^^^^
ValueError: invalid literal for int() with base 10: '4O96'
While reading the VLAN of interface Gi0/3

Python 3.11 also brought exception groups (PEP 654). They're useful when you work with many devices and several can fail for different reasons. ExceptionGroup bundles several exceptions, and except* handles each type separately:

def back_up_all(devices):
    errors = []
    for host, status in devices.items():
        if status == "timeout":
            errors.append(TimeoutError(f"{host}: no response"))
        elif status == "auth":
            errors.append(PermissionError(f"{host}: credentials rejected"))
    if errors:
        raise ExceptionGroup("Some backups failed", errors)

devices = {"R1": "ok", "R2": "timeout", "SW1": "auth", "SW2": "timeout"}

try:
    back_up_all(devices)
except* TimeoutError as group:
    for e in group.exceptions:
        print("Retry:", e)
except* PermissionError as group:
    for e in group.exceptions:
        print("Check credentials:", e)
# → Retry: R2: no response
# → Retry: SW2: no response
# → Check credentials: SW1: credentials rejected

Unlike except, several except* blocks can run for the same group. It's an advanced tool: you'll use it mostly with concurrent programming, for example with asyncio.TaskGroup.

The exception hierarchy

The built-in exceptions form a class tree. Since an except catches the given type and all its subclasses, knowing the tree helps you choose. For example, except OSError also catches FileNotFoundError and TimeoutError. This is a summary of the most useful branches in Python 3.14:

BaseException
 ├── BaseExceptionGroup
 ├── GeneratorExit
 ├── KeyboardInterrupt
 ├── SystemExit
 └── Exception
      ├── ArithmeticError
      │    ├── FloatingPointError
      │    ├── OverflowError
      │    └── ZeroDivisionError
      ├── AssertionError
      ├── AttributeError
      ├── EOFError
      ├── ExceptionGroup [BaseExceptionGroup]
      ├── ImportError
      │    └── ModuleNotFoundError
      ├── LookupError
      │    ├── IndexError
      │    └── KeyError
      ├── MemoryError
      ├── NameError
      │    └── UnboundLocalError
      ├── OSError
      │    ├── ConnectionError
      │    │    ├── ConnectionRefusedError
      │    │    └── ConnectionResetError
      │    ├── FileNotFoundError
      │    ├── PermissionError
      │    └── TimeoutError
      ├── RuntimeError
      │    ├── NotImplementedError
      │    └── RecursionError
      ├── StopIteration
      ├── SyntaxError
      │    └── IndentationError
      │         └── TabError
      ├── TypeError
      ├── ValueError
      │    └── UnicodeError
      │         ├── UnicodeDecodeError
      │         └── UnicodeEncodeError
      └── Warning
           ├── DeprecationWarning
           ├── SyntaxWarning
           └── UserWarning

The 4 branches that hang directly from BaseException aren't program errors but signals to stop: sys.exit() raises SystemExit, and Ctrl+C raises KeyboardInterrupt. That's why your exceptions inherit from Exception and, at most, you catch Exception, never BaseException.

You can check which branch any exception belongs to with its __mro__ attribute:

for exc in (FileNotFoundError, ConnectionRefusedError, KeyError, KeyboardInterrupt):
    print(exc.__name__, "→", " → ".join(c.__name__ for c in exc.__mro__[1:-1]))
# → FileNotFoundError → OSError → Exception → BaseException
# → ConnectionRefusedError → ConnectionError → OSError → Exception → BaseException
# → KeyError → LookupError → Exception → BaseException
# → KeyboardInterrupt → BaseException
Python 3.14 update. The book's list included StandardError, EnvironmentError, IOError and WindowsError as separate classes. StandardError disappeared in Python 3, and the rest were unified into OSError (PEP 3151), which gained subclasses such as ConnectionError and TimeoutError. GeneratorExit now inherits from BaseException. New ones include, among others, ModuleNotFoundError (3.6), RecursionError (3.5) and exception groups (3.11).

Challenge

Answer before you open the solution.

1. A traceback has 12 lines. Which one do you read first?

The last one. It shows the exception type and its message. Then you go up through the calls until you find the line in your code that caused it.

2. What's the difference between else and finally in a try?

else only runs if there was no exception; finally always runs. The first is for the success path and the second is for cleanup.

3. Is except TimeoutError, OSError as e: valid in Python 3.14?

No. Leaving out the parentheses is only allowed when there's no as. Write except (TimeoutError, OSError) as e:.

4. You migrate a script with except ValueError, e:, and in 3.14 it doesn't raise a syntax error. Is it OK?

No. It now means "catch ValueError or the type stored in e", and it fails with NameError when the error occurs. Change it to except ValueError as e:.

5. You create class NoResponse(BaseException). What problem can it cause?

An except Exception won't catch it. Your own exceptions should inherit from Exception or one of its subclasses.

Key takeaways

  • You read a traceback from the bottom up: type and message, then the chain of calls.
  • try/except catches specific errors; avoid a bare except:.
  • Group types in a tuple and use as to get the object; in 3.14, without as, you can drop the parentheses.
  • else for success, finally for cleanup, and never return inside finally.
  • Raise with raise Type("message"), chain with from and add context with add_note().
  • Your exceptions inherit from Exception; ExceptionGroup and except* handle several failures at once.

In the next chapter, you'll split your code into modules and packages, and install third-party libraries in a virtual environment.

Official resources

Source and credits. This course is based on the book Python para todos by Raúl González Duque, published under the Creative Commons Attribution 2.5 Spain license. The original book was written for Python 2.5. Jesús Espinoza, with AI assistance, brought it to Python 3.14: he rewrote every chapter in his own words, replaced the examples with networking cases, updated the syntax and the modules that no longer exist, fixed errors in the original and tested all the code with Python 3.14.6 against the official documentation.

Navigate