How do you test that a Python function throws an exception?
Interview Questions practice on Codemia
Over 8,000 real interview questions from top companies, searchable by company and role.
Introduction
To test that a Python function raises an exception, call it inside an assertion that expects that exception. The two most common tools are unittest.TestCase.assertRaises from the standard library and pytest.raises from pytest.
The key idea is not just "the test should fail if something goes wrong." A good exception test verifies that the right exception is raised for the right reason.
Example Function Under Test
Suppose you have a function that rejects empty names:
The test should prove that invalid input raises ValueError.
Using unittest
With unittest, use assertRaises as a context manager:
This is the standard-library solution and works well in projects that already use unittest.
Using pytest
With pytest, the equivalent is:
This is shorter and is one reason many Python projects prefer pytest.
Assert the Message When It Matters
Sometimes the exception type alone is not enough. If your API contract depends on a specific message, assert that too.
With unittest:
With pytest:
Do this when the message is part of the behavior you care about, not just because it is possible.
Custom Exceptions Work the Same Way
If your code raises a custom exception, test it the same way:
Then:
The testing pattern does not change just because the exception class is your own.
Avoid Broad Exception Assertions
This is technically valid but usually too weak:
It passes for almost any failure, including the wrong one. Prefer the narrowest useful exception type:
- '
ValueErrorinstead ofException' - '
FileNotFoundErrorinstead ofOSError' - your domain-specific exception instead of a generic base class
Specificity makes tests protect behavior rather than just "something exploded."
Parameterize Repeated Failure Cases
If several inputs should fail in the same way, parameterization keeps the test clean:
That is much easier to extend than copying the same test body several times.
Common Pitfalls
The most common mistake is putting too much code inside the raises block. Keep only the call that is supposed to fail there, or the test may pass for the wrong reason.
Another mistake is asserting an overly broad exception type such as Exception. That makes tests weak and hides regressions.
Teams also forget to test the successful path. If a function should raise on bad input and return a value on good input, both behaviors deserve tests.
Finally, do not catch the exception inside the function and then test for printed output unless printing is the intended API. If failure should be observable to callers, let the exception propagate and test that directly.
Summary
- Use
assertRaisesinunittestorpytest.raisesinpytest. - Assert the specific exception type, not a broad catch-all.
- Check the message only when it is part of the expected behavior.
- Parameterize repeated bad-input cases to keep tests concise.
- Keep the exception assertion focused on the single call that is meant to fail.
Related reading
- How do you use Keras LeakyReLU in Python?
- How do you use the ellipsis slicing syntax in Python?
- How do you visualize a ward tree from sklearn.cluster.ward_tree?
- How do you write tests for the argparse portion of a python module?
- How do you unit test private methods?
- How does Junit Rule work?
- How do you test to see if a double is equal to NaN?
- How does distributed tensorflow work ? Issue with tf.train.Server
.png&w=3840&q=75)
Tackling System Design Interview Problems
A short course that equips you with the skills to approach system design interviews methodically.
Start the free courseTrack what you have practised
A free account saves your progress, solutions and study plan across every problem on Codemia.
Interview Questions practice on Codemia
Over 8,000 real interview questions from top companies, searchable by company and role.