Assert that Python code raises an exception with pytest

Use pytest.raises to check exception types, match error messages, inspect exception details, and avoid assertions that never run.

Best practices
Assert that Python code raises an exception with pytest illustration

Wrap the operation in with pytest.raises(ExpectedError):. The test passes this check when the block raises the expected exception type or a subclass; it fails if no exception is raised or the exception type does not match.

Check the exception type

import pytest

def divide(a, b):
    if b == 0:
        raise ValueError('Divisor cannot be zero')
    return a / b

def test_divide_by_zero():
    with pytest.raises(ValueError):
        divide(10, 0)

Keep the block focused on the operation expected to fail, so an earlier unrelated exception cannot satisfy the assertion accidentally.

Check the message and exception object

def test_error_message():
    with pytest.raises(ValueError, match=r'^Divisor cannot be zero$'):
        divide(10, 0)

def test_exception_detail():
    with pytest.raises(ValueError) as exc_info:
        divide(10, 0)
    assert 'zero' in str(exc_info.value)
    assert exc_info.type is ValueError

match uses regular-expression search semantics. Anchors require the whole message to match; without them, a matching substring is enough. Use re.escape(expected_text) when the message should be treated literally despite containing regex punctuation. The explicit type identity check is useful only when a subclass should not be accepted.

Accept more than one exception type

with pytest.raises((ValueError, TypeError)):
    int(None)

Only broaden the expected types when both represent the intended contract. Catching Exception indiscriminately can hide bugs.

FAQ

Will code after the failing call run inside the with block?

No. Raising the exception exits the block. Put assertions about exc_info.value after the block, where they can actually execute.

How do I assert that nothing is raised?

Call the function normally. An unexpected exception fails the test. Assert the returned value or side effects as well when they are part of the behavior you want to verify.

See pytest.raises reference.

Get a tailored plan

Contact us

Join the community

Scan with WeChat
to join the community

Try Guance

Start online and pay only for what you use.

Get started

Choose a Guance plan

Code hosting