Use TestCase.assertRaises from the unittest module, for example:

import mymod

class MyTestCase(unittest.TestCase):
    def test1(self):
        self.assertRaises(SomeCoolException, mymod.myfunc)
Answer from Moe on Stack Overflow
🌐
pytest
docs.pytest.org › en › 7.1.x › how-to › assert.html
How to write and report assertions in tests — pytest documentation
and if you need to have access to the actual exception info you may use: def test_recursion_depth(): with pytest.raises(RuntimeError) as excinfo: def f(): f() f() assert "maximum recursion" in str(excinfo.value)
🌐
Medium
medium.com › data-science › python-exception-testing-clean-and-effective-methods-86799da86b90
Python Exception Testing: Clean and Effective Methods | by Naomi Kriger | TDS Archive | Medium
July 24, 2023 - from contextlib import nullcontext as does_not_raise import pytest from operations import divide @pytest.mark.parametrize( "num_1, num_2, expected_result, exception, message", [ (30, 2.5, 12.0, does_not_raise(), None), (10.5, 0, None, pytest.raises(ZeroDivisionError), "float division by zero"), ("a", 10.5, None, pytest.raises(TypeError), "at least one of the inputs is not a number: a, 10.5") ], ids=["valid inputs", "divide by zero", "not a number input"] ) def test_division(num_1, num_2, expected_result, exception, message): with exception as e: result = divide(num_1, num_2) assert message is None or message in str(e) if expected_result is not None: assert result == expected_result
🌐
Pytest with Eric
pytest-with-eric.com › introduction › pytest-assert-exception
How To Test Python Exception Handling Using Pytest Assert (A Simple Guide) | Pytest with Eric
March 23, 2026 - But, with more exception handling comes challenges in testing. How do you handle unpredictability in code execution and flow? What about error propagation to the rest of the stack? Do you raise errors or handle them? And how do you ensure to display the correct and helpful type of error? This is very important, particularly when dealing with User facing tooling like APIs and response codes. Pytest assert exception handling can help with this.
🌐
Python
docs.python.org › 3 › library › unittest.html
unittest — Unit testing framework
Test that an exception is raised when callable is called with any positional or keyword arguments that are also passed to assertRaises(). The test passes if exception is raised, is an error if another exception is raised, or fails if no exception ...
🌐
GeeksforGeeks
geeksforgeeks.org › python › test-if-a-function-throws-an-exception-in-python
Test if a function throws an exception in Python - GeeksforGeeks
July 15, 2025 - Just pass the exception, the callable function and the parameters of the callable function as keyword arguments that will elicit the exception. ... assertRaises(exception) Make a function call that should raise the exception with a context.
🌐
pytest
docs.pytest.org › en › stable › how-to › assert.html
How to write and report assertions in tests - pytest documentation
In order to write assertions about raised exceptions, you can use pytest.raises() as a context manager like this:
Find elsewhere
🌐
Towards Data Science
towardsdatascience.com › home › artificial intelligence › practical python: try, except, and assert
Practical Python: Try, Except, and Assert | Towards Data Science
November 14, 2020 - The try and except blocks are used to handle exceptions. The assert is used to ensure the conditions are compatible with the requirements of a function.
🌐
Python.org
discuss.python.org › ideas
Asserting exact exception instances - Ideas - Discussions on Python.org
March 9, 2025 - There are two helpers in unittest.TestCase for asserting that exceptions are raised and properties of them: assertRaises checks that an exception is raised and asserts its type assertRaisesRegex checks that an exception is raised and matches its type and str I generally try to assert something about the message just to make sure the test doesn’t accidentally pass by raising the same exception in a different way, so I almost always use assertRaisesRegex.
🌐
Inspired Python
inspiredpython.com › article › assertions-and-exceptions-are-not-the-same
Assertions and Exceptions are not the same • Inspired Python
Saying that, it’s easy to see why people get confused because assert itself raises an exception called AssertionError which does little to resolve the confusion between the two modes of control flow.
🌐
GeeksforGeeks
geeksforgeeks.org › python › python-assertion-error
Assertion Error - Python - GeeksforGeeks
June 26, 2026 - Explanation: The failed assertion raises an exception, which is caught by except AssertionError as e, allowing the program to continue gracefully.
🌐
Tutorialspoint
tutorialspoint.com › python › python_assertions.htm
Python - Assertions
Assertions can be caught and handled like any other exception using a try-except block.
🌐
pytest
docs.pytest.org › en › 6.2.x › assert.html
The writing and reporting of assertions in tests — pytest documentation
and if you need to have access to the actual exception info you may use: def test_recursion_depth(): with pytest.raises(RuntimeError) as excinfo: def f(): f() f() assert "maximum recursion" in str(excinfo.value)
🌐
Real Python
realpython.com › ref › builtin-exceptions › assertionerror
AssertionError | Python’s Built-in Exceptions – Real Python
AssertionError is a built-in exception that occurs when an assert statement fails. The assert statement checks that a condition is truthy. If the condition is falsy, then Python raises an AssertionError.
🌐
TutorialsPoint
tutorialspoint.com › unittest_framework › unittest_framework_exceptions_test.htm
UnitTest Framework - Exceptions Test
To catch any of a group of exceptions, a tuple containing the exception classes may be passed as exception. In the example below, a test function is defined to check whether ZeroDivisionError is raised. import unittest def div(a,b): return a/b class raiseTest(unittest.TestCase): def testraise(self): self.assertRaises(ZeroDivisionError, div, 1,0) if __name__ == '__main__': unittest.main()
🌐
Gitlab
ongspxm.gitlab.io › blog › 2016 › 11 › assertraises-testing-for-errors-in-unittest
assertRaises - testing for errors in unittest
November 16, 2016 - import unittest def func(): raise Exception('lets see if this works') class ExampleTest(unittest.TestCase): def test_error(self): self.assertRaises(Exception, lambda:func()) if __name__=='__main__': unittest.main() But lambda is a whole new monster on its own. It doesn't seem to be the right tool to use just as a wrapper for the function. This is a much more appropriate and pythonic way of using assertRaises.
Author: ericsalesdeandrade