This will work. But it's kind of crazy.

try:
    assert False, "A Message"
except AssertionError, e:
    raise Exception( e.args )

Why not the following? This is less crazy.

if not someAssertion: raise Exception( "Some Message" )

It's only a little wordier than the assert statement, but doesn't violate our expectation that assert failures raise AssertionError.

Consider this.

def myAssert( condition, action ):
    if not condition: raise action

Then you can more-or-less replace your existing assertions with something like this.

myAssert( {{ the original condition }}, MyException( {{ the original message }} ) )

Once you've done this, you are now free to fuss around with enable or disabling or whatever it is you're trying to do.

Also, read up on the warnings module. This may be exactly what you're trying to do.

Answer from S.Lott on Stack Overflow
🌐
Codementor
codementor.io › python › tutorial › python-custom-exception
Tutorial: How to Create Custom Exceptions in Python | Codementor
raise AssertionError("color of car1: ", car1.color, " and color of car2: ", car2.color) AssertionError: ('color of car1: ', 'blue', ' and color of car2: ', 'red') Need Ankur’s help? Book a 1-on-1 session! ... Passionate python programmer and lead developer of pgmpy.
🌐
Better Programming
betterprogramming.pub › how-to-overwrite-asserterror-in-python-and-use-custom-exceptions-c0b252989977
How to Overwrite AssertionError in Python and Use Custom Exceptions | by Marcin Kozak | Better Programming
November 29, 2022 - In this article, I will show you how simple it can be to make the assert statement raise a different exception instead of AssertionError. I think you… ... Advice for programmers. ... A full professor, interdisciplinary researcher, data scientist, statistician, Python, R and Go developer, open-source contributor — and a devoted writer
🌐
pytest
docs.pytest.org › en › stable › how-to › assert.html
How to write and report assertions in tests - pytest documentation
The pytest.raises() call will succeed, ... however the following assert statement will catch the problem. You can pass a match keyword parameter to the context-manager to test that a regular expression matches on the string representation of an exception (similar to the ...
🌐
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 - We’ve seen a few cases of asserting inbuilt exceptions using Pytest. But what about defining and testing your own exceptions. In Python, we can define our own custom exceptions in the following way.
🌐
Medium
medium.com › @jyotijingar › understanding-raise-assert-and-custom-exceptions-in-python-ac67775e23d6
Understanding raise, assert, and Custom Exceptions in Python | by jyoti jingar | Medium
August 23, 2025 - 👉 Use assert when you want to validate assumptions during development/testing. In production, assertions are usually disabled for efficiency. Sometimes built-in exceptions (ValueError, TypeError, etc.) aren’t enough.
🌐
Real Python
realpython.com › python-exceptions
Python Exceptions: An Introduction – Real Python
March 18, 2026 - After seeing the difference between syntax errors and exceptions, you learned about various ways to raise, catch, and handle exceptions in Python. You also learned how you can create your own custom exceptions. In this article, you gained experience working with the following exception-related keywords: raise allows you to raise an exception at any time. assert enables you to verify if a certain condition is met and raises an exception if it isn’t.
🌐
GeeksforGeeks
geeksforgeeks.org › python-assertion-error
Assertion Error - Python - GeeksforGeeks
April 7, 2025 - If the condition fails (i.e., if y is 0), the exception is caught and the error message is printed. Assertions are often used in testing to validate that functions produce the expected results. Consider the following example for solving a quadratic equation. ... import math def quadratic_roots(a, b, c): try: assert a != 0, "Not a quadratic equation: coefficient of x^2 cannot be 0" D = (b * b - 4 * a * c) assert D >= 0, "Roots are imaginary" r1 = (-b + math.sqrt(D)) / (2 * a) r2 = (-b - math.sqrt(D)) / (2 * a) print("Roots of the quadratic equation are:", r1, r2) except AssertionError as error: print(error) quadratic_roots(-1, 5, -6) # Expected valid roots quadratic_roots(1, 1, 6) # Expected error: roots are imaginary quadratic_roots(2, 12, 18) # Expected valid roots
Find elsewhere
🌐
DEV Community
dev.to › wangonya › asserting-exceptions-with-pytest-8hl
Asserting Exceptions with Pytest - DEV Community
January 29, 2019 - In your case ValueError (or a custom exception) is probably more appropriate: Raised when an operation or function receives an argument that has the right type but an inappropriate value · A bonus tip: pytest.raises accepts an argument that ...
🌐
pytest
docs.pytest.org › en › 7.1.x › how-to › assert.html
How to write and report assertions in tests — pytest documentation
This allows you to use the idiomatic python constructs without boilerplate code while not losing introspection information. However, if you specify a message with the assertion like this: assert a % 2 == 0, "value was odd, should be even" then no assertion introspection takes places at all and the message will be simply shown in the traceback. See Assertion introspection details for more information on assertion introspection. In order to write assertions about raised exceptions, you can use pytest.raises() as a context manager like this:
🌐
Delft Stack
delftstack.com › home › howto › python › python assert exception
Python Assert Exception | Delft Stack
October 10, 2023 - The example code above used assertRaises() with keyword arguments. We passed to it the ZeroDivisionError exception expected after trying to divide a number with zero. We imported the operator function used with the floordiv operator function as the second argument.
🌐
Python
docs.python.org › 3 › builtins › exceptions.html
Built-in Exceptions — Python 3.14.7 documentation
In Python, all exceptions must be instances of a class that derives from BaseException. In a try statement with an except clause that mentions a particular class, that clause also handles any excep...
🌐
Medium
medium.com › pyprospectives › python-part39-custom-exception-and-assert-statement-1acfd8c625b0
Python(Part39-Custom Exception and Assert statement) | by Tejasvi Navale | PyProspectives | Medium
March 19, 2025 - In Python, you can create custom exceptions by defining a new class that inherits from the built-in Exception class. This allows you to raise and handle exceptions that are specific to your application or use case.
🌐
pytest
docs.pytest.org › en › 6.2.x › assert.html
The writing and reporting of assertions in tests — pytest documentation
This allows you to use the idiomatic python constructs without boilerplate code while not losing introspection information. However, if you specify a message with the assertion like this: assert a % 2 == 0, "value was odd, should be even" then no assertion introspection takes places at all and the message will be simply shown in the traceback. See Assertion introspection details for more information on assertion introspection. In order to write assertions about raised exceptions, you can use pytest.raises() as a context manager like this:
🌐
Towards Data Science
towardsdatascience.com › home › latest › practical python: try, except, and assert
Practical Python: Try, Except, and Assert | Towards Data Science
January 19, 2025 - 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.
🌐
DNMTechs
dnmtechs.com › customizing-pythons-assert-behavior-in-python-3-exception-based-approach
Customizing Python’s `assert` Behavior in Python 3: Exception-Based Approach – DNMTechs – Sharing and Storing Technology Knowledge
In this case, since x is not equal ... is displayed: ... Python 3 introduced a way to customize the behavior of assert by allowing developers to define their own exception classes....
🌐
Real Python
realpython.com › python-raise-exception
Python's raise: Effectively Raising Exceptions in Your Code – Real Python
October 20, 2025 - You use raise to initiate exceptions for error handling or to propagate existing exceptions. You can raise custom exceptions by defining new exception classes derived from Exception. The difference between raise and assert lies in their use.
Top answer
1 of 1
17

You are trying to use methods of the TestCase class without creating an instance; those methods are not designed to be used in that manner.

unittest.TestCase.assertRaises is an unbound method. You'd use it in a test method on a TestCase class you define:

class DemoTestCase(unittest.TestCase):
    def test_foobar(self):
        with self.assertRaises(DataException):
            foobar()

The error is raised because unbound methods do not get self passed in. Because unittest.TestCase.assertRaises expects both self and a second argument named expected_exception you get an exception as DataException is passed in as the value for self.

You do now have to use a test runner to manage your test cases; add

if __name__ == '__main__':
    unittest.main()

at the bottom and run your file as a script. Your test cases are then auto-discovered and executed.

It is technically possible to use the assertions outside such an environment, see Is there a way to use Python unit test assertions outside of a TestCase?, but I recommend you stick to creating test cases instead.

To further verify the codes and message on the raised exception, assign the value returned when entering the context to a new name with with ... as <target>:; the context manager object captures the raised exception so you can make assertions about it:

with self.assertRaises(DataException) as context:
    foobar()

self.assertEqual(context.exception.code, 'E101')
self.assertEqual(
    context.exception.msg,
    'There is no data at all for these constraints')

See the TestCase.assertRaises() documentation.

Last but not least, consider using subclasses of DataException rather than use separate error codes. That way your API users can just catch one of those subclasses to handle a specific error code, rather than having to do additional tests for the code and re-raise if a specific code should not have been handled there.