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
Discussions

python - In Python3, how do you test exception handling within a unit test? - Stack Overflow
I have several unit tests that I'm working on for an api. The tests use @patch to mock the api calls. Some of the tests I wish to create should trigger exceptions. How do I handle that in a unit te... More on stackoverflow.com
🌐 stackoverflow.com
python - What is the difference between unit testing and handling exceptions - Software Engineering Stack Exchange
I have spent two full days now trying to understand the difference between unit testing and handling exception, but I can't get it. Things I have understood (or I think I have): Unit testing tests More on softwareengineering.stackexchange.com
🌐 softwareengineering.stackexchange.com
Python unittest an error-handling function
I am a great believer in TDD but I don't think it's worth unit-testing something so trivial. If I did want to test it, I'd pass in a mock Exception class. More on reddit.com
🌐 r/learnpython
12
1
September 10, 2023
Unit Test for Expected Exception in Python - Ask a Question - TestMu AI (formerly LambdaTest) Community
How can one write a unit test in Python that fails only if a function does not throw an expected exception? In Python, how can I create a unit test to ensure that a function raises a specific exception? I want the test to fail only if the exception is not raised. More on community.testmuai.com
🌐 community.testmuai.com
0
October 2, 2024
🌐
Python
docs.python.org › 3 › library › unittest.html
unittest — Unit testing framework
Any other exceptions will be treated as errors. Tests can be numerous, and their set-up can be repetitive. Luckily, we can factor out set-up code by implementing a method called setUp(), which the testing framework will automatically call for every single test we run: import unittest class WidgetTestCase(unittest.TestCase): def setUp(self): self.widget = Widget('The widget') def test_default_widget_size(self): self.assertEqual(self.widget.size(), (50,50), 'incorrect default size') def test_widget_resize(self): self.widget.resize(100,150) self.assertEqual(self.widget.size(), (100,150), 'wrong size after resize')
🌐
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()
🌐
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 - Here, in the output the “.” on the first line of output means that test has passed and the function has thrown an exception of TypeError while adding an integer value and a string value. ... import unittest class MyTestCase(unittest.TestCase): # Returns false if 1 + 1 raises no Exception def test_1(self): with self.assertRaises(Exception): 1 + 1 if __name__ == '__main__': unittest.main()
🌐
Towards Data Science
towardsdatascience.com › home › data science › how to test if a function throws an exception in python
How To Test If a Function Throws An Exception in Python | Towards Data Science
October 11, 2022 - In today's article we will demonstrate how to write test cases that test whether a function raises the expected Exception when a certain event occurs. More specifically, we will showcase how to do so using two of the most popular test packages in Python, namely unittest and pytest.
🌐
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
Find elsewhere
🌐
W3Resource
w3resource.com › python-interview › how-do-you-handle-exceptions-in-unit-tests.php
Exception handling in Unit tests: Best practices
Use Specific Assertion Methods: ... check for it. For example, in unittest, you can use assertRaises() or assertRaisesRegex() to verify that a specific exception is raised....
🌐
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): with self.assertRaises(Exception): func() if __name__=='__main__': unittest.main()
🌐
Towards Data Science
towardsdatascience.com › home › latest › python exception testing: clean and effective methods
Python Exception Testing: Clean and Effective Methods | Towards Data Science
January 22, 2025 - In this tutorial, we will explore practical and effective methods to test Python code that raises and does not raise exceptions, verifying the accuracy of the exception messages, and covering both pytest and unittest, with and without parameterized tests for each framework.
🌐
Python Clear
pythonclear.com › home › unittest › 2 ways to use python unittest assertraises() in python
2 Ways to use Python Unittest assertRaises() in Python - Python Clear
December 29, 2023 - The assertRaises method allows us to do this by passing it an additional argument: a function that receives the raised exception as an argument and verifies its contents. Let’s see how this works with our example from the previous section: import unittest def test_to_upper(self): with self.assertRaises(ValueError): to_upper('')
🌐
GeeksforGeeks
geeksforgeeks.org › python-exceptional-conditions-testing-in-unit-tests
Python | Exceptional Conditions Testing in Unit Tests - GeeksforGeeks
June 12, 2019 - They record information about usage ... MagicMock(return_value = 10) p ... In Python, exceptions are used to handle errors that occur during the execution of a program....
Top answer
1 of 2
3

Let's look at your get_turn method:

def get_turn(self):
    try:
        assert self.turn >= 0
    except ValueError:
        print('turn number must be positive')

There are a couple problems here:

  • In most languages, assertions only execute in debug mode. If you run Python with the -O flag, your assertion will never execute!
  • A failed assertion will raise an AssertionError, not a ValueError
  • This should not have been allowed to be in an invalid state in the first place. If self.turn is negative, then the actual bug happened somewhere else.

Here's how I would rewrite it:

def set_turn(self, turn):
    if turn < 0:
        raise ValueError('Turn number must be nonnegative')
    self.turn = int(turn)

def get_turn(self):
    assert self.turn >= 0   # This should never fail. If it does, you made a programming mistake.
    return self.turn

And then in your unit tests, you could write calls to make sure they behave as expected.

2 of 2
6

Exception handling and unit testing solve different problems:

  • Exception Handling: Allows a running program to recover from an exceptional condition (like expecting to be able to open a file but it is open in another program).
  • Unit Tests: Tests the behavior of small parts (units) of your program to make sure they behave the way you expect.

Exception handling is a run time concern, while unit tests are a build time concern.

The two can work together. For example, let's say you have a utility that attempts to move files from one place to another, and verify that they are bit for bit the same. In your utility, you need to scan for the available files, and then work on them one by one.

A number of things can cause the utility to not be able to copy a file:

  • The file is in use by another process
  • You do not have permissions to delete the file from its present location, or write it to the destination
  • If you have more than one utility running at once, the file could be gone by the time you get to it in your loop

Those are all exceptions. You have to decide whether any of those exceptions should cause your utility to stop processing. For example, the final exception is something we don't want to stop prematurely with, and it is probably OK to skip a file if another process has it. The permissions thing really prevents your utility from doing its job, so you'll need to stop if that's the case.

In your unit tests, you would set up a scenario where each of those conditions would be met, and then assert that the application behaves appropriately:

  • Unit test 1 sets up a source and destination directory where everything is set up for a successful copy. It works, no exception handling required!
  • Unit test 2 sets up a source and destination directory, and then puts a lock on the source file. It fails, so you need to add exception handling to your utility to handle the lock (i.e. skip the existing file and move on
  • Unit test 3-5 sets up source and destination directory and a source file, but changes the permissions (source, destination, both) and asserts that the utility stops as soon as it realizes it can't copy any files. If the exception handling you put in before isn't too broad, then this should work. If not, you have to change your application to make all the tests pass.
  • Unit test 6 would be a bit more difficult to instrument since you would need to know when the source directory scan is complete, but it would set up source and destination directories, source file and then delete the source file after the scan is complete but before the move operation was performed. If the application ends early it fails, so you need to add exception handling, or at least an exists check before the copy/verify/delete operation is complete.

As you can see they are not mutually exclusive concepts to improve your application. However, they serve very different purposes.


I will say using exception handling where a simple if statement is more appropriate, you should change your code. In the example you provided there was a snippet that looked like this:

    try:
        assert self.turn >= 0
    except ValueError:
        print('turn number must be positive')

That would be a misapplication of an assert, particularly because you are not letting the exception leave the method. That could would be much cleaner, and execute faster (especially in loops) like this:

    if selt.turn < 0:
        print('turn number must be positive')

That code provides the same effect in a more readable way, that doesn't have the overhead of exception handling. Exception handling is expensive.

Now, if you wanted that to be an exceptional case that stops the game because now the game is in an undetermined state, you should not catch the exception in that code, and let whoever is calling the code deal with it. That would simply look like this:

    assert(self.turn >= 0, 'turn number must be positive')
🌐
Reddit
reddit.com › r/learnpython › python unittest an error-handling function
r/learnpython on Reddit: Python unittest an error-handling function
September 10, 2023 -

Hi all, I've written an error-handling function called prettify_error. This function is called in a few try-except blocks when doing some file work, such as reading or writing. So, the function takes in an Exception and an optional file_mode parameter. I did this to make the function more robust in case I have to call it in the future with doing other things that could throw an exception. Anyway, here's the function code:

def prettify_error(error: Exception, file_mode: str = ""):
"""Helper function to prettify an error or exception

This function will take an Exception and create a more human-readable
output for the error

Args:
    error (Exception): The Exception that was caught (might be most likely
    through a try-except block).

    file_mode (str, optional): If the Exception was caught while working
    with files, this parameter will tell which file mode or what action was
    being taken. Acceptable values are "r" for reading, "w" for writing.
    Defaults to "". If the default value is used or a non-acceptable value
    is used, only the Exception will be returned without any extra
    messaging.

Returns:
    str: The Exception printed out in a way that makes sense
"""
return_message = ""
match file_mode:
    case "r":
        return_message += "Unable to read startup data. Error information is below:\n"
    case "w":
        return_message += "Unable to write startup data. Error information is below:\n"
    case _:
        pass
return_message += str(type(error).__name__) + " - " + str(error)
return return_message

I'm now trying to write unittest test functions for it but I'm not sure how to call it. I looked up some stuff and I read about the unittest self.assertRaises function as well as creating custom Exception classes that extend the base class. But, I don't think the first will work since I'm really testing for the return_message variable and will be using self.assertEquals instead. I'm also going to have 3 test functions, one for a file_mode value of default, one for a value of "r", and one for a value of "w". I also feel like creating a customer Exception class is overkill.

What do you think? Is that the best way to test prettify_error, by creating a custom Exception class and passing that in during my tests? Or can I pass in a specific Exception, like Exception.TypeError?

Thanks in advance.

🌐
Rip Tutorial
riptutorial.com › testing exceptions
Python Language Tutorial => Testing Exceptions
This has as advantage that more code can be executed, but should be used with care since multiple functions can use the same exception which can be problematic. An example: with self.assertRaises(WrongInputException): convert2number("not a number") This first has been implemented in the following test case: import unittest class ExceptionTestCase(unittest.TestCase): def test_wrong_input_string(self): self.assertRaises(WrongInputException, convert2number, "not a number") def test_correct_input(self): try: result = convert2number("56") self.assertIsInstance(result, int) except WrongInputException: self.fail()
🌐
Codemia
codemia.io › home › knowledge hub › how do you test that a python function throws an exception?
How do you test that a Python function throws an exception? | Codemia
January 2, 2025 - Here's a quick example: ... 1def ... unittest framework in Python, which is built into the standard library, provides a way to test whether a function raises an exception as expected using assertRaises....
🌐
TestMu AI
community.testmuai.com › ask a question
Unit Test for Expected Exception in Python - Ask a Question - TestMu AI (formerly LambdaTest) Community
October 2, 2024 - How can one write a unit test in Python that fails only if a function does not throw an expected exception? In Python, how can I create a unit test to ensure that a function raises a specific exception? I want the test …
🌐
Readthedocs
testfixtures.readthedocs.io › en › latest › exceptions.html
Testing exceptions - testfixtures 12.3.0 documentation
This will contain the actual exception raised and can be used to inspect parts of it: >>> import sys >>> from testfixtures import ShouldRaise >>> with ShouldRaise() as s: ... sys.exit(42) >>> s.raised.code 42 · If you are working in a traditional unittest environment and want to check that a particular test function raises an exception, you may find the decorator suits your needs better: