How to Test Exceptions in Python with pytest.raises

Learn the pytest.raises pattern to assert that specific exceptions are raised and validate their messages.

Easy Python 3.9+ Aug 9, 2026 Errors & debugging 15 views 0 copies

Requires third-party packages — install first
pip install pytest

Python code

23 lines
Python 3.9+
import pytest


def divide(a: int, b: int) -> float:
    if b == 0:
        raise ValueError("Cannot divide by zero")
    return a / b


def test_divide_by_zero_raises():
    with pytest.raises(ValueError, match="Cannot divide by zero"):
        divide(10, 0)


def test_divide_by_zero_raises_exact_match():
    with pytest.raises(ValueError) as exc_info:
        divide(10, 0)
    assert str(exc_info.value) == "Cannot divide by zero"
    assert exc_info.type is ValueError


if __name__ == "__main__":
    pytest.main([__file__, "-v"])

Output

stdout
============================= test session starts ==============================
platform linux -- Python 3.11.0, pytest-7.4.0, pluggy-1.0.0
rootdir: /path/to/tests
collected 2 items

test_exceptions.py ..                                                    [100%]

============================== 2 passed in 0.02s ==============================

How it works

pytest.raises(ValueError) acts as a context manager; the block inside must raise the expected exception or the test fails. Using match allows you to assert a regex pattern on the exception message, while capturing the exception with as exc_info lets you inspect its type and string value. Always keep the exception type specific to catch real bugs, not broad Exception.

Common mistakes

  • Forgetting to import pytest, causing a NameError.
  • Using a broad exception type like `Exception` when a specific one is expected, hiding unrelated failures.
  • Neglecting to check the exception message when exact validation is needed.

Variations

  1. Use `pytest.raises(ValueError, match='^...$')` to enforce a full regex match.
  2. Call `pytest.raises(ValueError)` as a function: `pytest.raises(ValueError, divide, 10, 0)` for simple cases.

Real-world use cases

  • Verifying that a payment gateway raises ValueError for invalid amounts.
  • Ensuring a config parser raises FileNotFoundError when a required file is missing.
  • Testing that API clients raise requests.HTTPError on non‑2xx responses.

Sponsored

Run locally

This sample needs third-party packages, so it cannot run in the browser IDE. Copy the code above, install the packages shown at the top, then run it in your own Python environment.

More from Errors & debugging

Related tutorials and quizzes for this topic.