How can I check if a Python function is throwing an exception?

Python Methods and Functions

We write a unittest that only fails if the function does not throw the expected exception.

We also check if the Python function throws an exception.

For example, see the example code that we embed in a Python wrapper to test Python type safety:


 import statement unittest class MyTestCase (unittest.TestCase): def test_1_cannot_a dd_int_and_str (the self): with self.assertRaises (a TypeError): 1 '1' + def test_2_cannot_add_int_and_str (the self): import statement operator self.assertRaises (TypeError, operator.add, 1, ' 1' ) unittest.main (exit = False) 

Running tests


And the terminal outputs the following &

 .. ---------------------------------------------- ------------------------ Ran 2 tests in 0.001s OK 

The first test uses assertRaises as a context manager that provides correct error detection and resolution during recording.

We could also write this without a context manager, see Test two. The first argument will be the type of error you expect to be called, the second argument will be the function you are testing, and the rest of the arguments and keyword arguments will be passed to that function.

It's much easier and clearer to just use the context manager. We see that, as we expect, trying to add 1 and 1 results in a TypeError.

Get Solution for free from DataCamp guru