How to Assert Exceptions in Python with pytest.raises

Use pytest.raises as a context manager to assert that a function raises an expected exception and inspect its message in pytest tests.

Easy Python 3.9+ Aug 9, 2026 Testing & modern typing 14 views 0 copies

Requires third-party packages — install first
pip install pytest

Python code

19 lines
Python 3.9+
import pytest

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

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

def test_divide_normal():
    assert divide(10, 2) == 5

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

Output

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

test_example.py::test_divide_by_zero PASSED                               [ 50%]
test_example.py::test_divide_normal PASSED                               [100%]

============================== 2 passed in 0.01s ===============================

How it works

pytest.raises(ValueError) wraps the call divide(10, 0) and fails the test if no ValueError is raised. Assigning the context to exc_info gives access to the raised exception via exc_info.value, letting you assert on its type and message. The context manager ensures the rest of the test only runs if the exception is raised, keeping your checks focused. This pattern is the standard way to validate error handling in pytest. It also works with any exception class and can match subclasses.

Common mistakes

  • Using `pytest.raises` without the `as exc_info` clause when you need to check the message.
  • Forgetting to call the function inside the `with` block, so a missing exception goes unnoticed.
  • Asserting on `exc_info.type` instead of `exc_info.value` for the message.

Variations

  1. Use `pytest.raises(ValueError, match='zero')` to check the message with a regex.
  2. Use `with pytest.raises(ValueError):` without capturing details when only the exception type matters.

Real-world use cases

  • Verifying that a config parser raises a clear error when a required key is missing.
  • Checking that an API client raises a custom exception on non-200 HTTP responses.
  • Validating that a payment processor rejects invalid amounts with the expected error.

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 Testing & modern typing

Related tutorials and quizzes for this topic.