pytest.raises: Testing Python Exceptions addresses a recurring problem in Python projects: Prove that invalid input fails in the expected way and at the expected point. This guide explains the mechanism, provides an executable example, and identifies the boundaries that keep an implementation reliable.

Concept and use case

pytest.raises is a context manager that fails when no compatible exception occurs. The match argument applies a regular expression to the textual representation.

For the related fundamentals, also read the pytest guide. Integration stays simpler when functions receive dependencies and data explicitly instead of relying on global state.

Practical example

import pytest


def divide(a: float, b: float) -> float:
    if b == 0:
        raise ValueError("divisor must not be zero")
    return a / b


def test_zero_divisor():
    with pytest.raises(ValueError, match="must not be zero") as exc:
        divide(10, 0)
    assert exc.value.args[0] == "divisor must not be zero"

Keep only the expected failing call inside the block. Then inspect exc.value for meaningful attributes on domain exceptions.

Important decisions

The correct choice depends on the public contract, expected volume, and failure behavior.

Consider concurrency, empty inputs, and partial failures. Document every limit that affects consumers and choose names that express intent.

Common mistakes

A minimal example does not replace bounds, error handling, and observability. A large block may catch the right exception type from the wrong line. Catching Exception makes the contract vague, while matching a full message makes tests brittle.

Avoid catching exceptions without context or returning partial output as if it were complete. An explicit failure is usually safer than silently incorrect data.

How to validate

Validate behavior, not only the happy path. Pair the invalid case with a valid case and decide whether subclasses are acceptable under the public contract.

The official documentation, accessed July 28, 2026, details the API and should remain the reference for future changes.