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.
pip install pytest
Python code
23 linesimport 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
============================= 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
- Use `pytest.raises(ValueError, match='^...$')` to enforce a full regex match.
- 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
More from Errors & debugging
- Catch RecursionError and Fail Gracefully in Python easy
- Catch ValueError and print friendly message in Python easy
- Collect Multiple Validation Errors in Python Before Raising medium
- Handle ValueError and ZeroDivisionError in Python with try except easy
- How to Add a Correlation ID to Logging Records in Python medium
- How to Assert Preconditions with Descriptive Messages in Python easy
Keep learning
Related tutorials and quizzes for this topic.