We test multiple exceptions to make sure our code handles different errors correctly. This helps catch bugs and improves program reliability.
0
0
Testing multiple exceptions in PyTest
Introduction
When a function can raise different errors depending on input.
When you want to confirm your code raises the right error for wrong data.
When testing error handling in user input validation.
When checking that your program fails safely under various bad conditions.
Syntax
PyTest
import pytest with pytest.raises((ExceptionType1, ExceptionType2)): # code that should raise one of the exceptions
You list exceptions inside a tuple to check for multiple possible errors.
The test passes if any one of the exceptions is raised.
Examples
This test passes because dividing by zero raises
ZeroDivisionError, which is in the tuple.PyTest
import pytest def test_divide(): with pytest.raises((ZeroDivisionError, TypeError)): result = 10 / 0 # raises ZeroDivisionError
This test passes because adding string and int raises
TypeError, which is in the tuple.PyTest
import pytest def test_add(): with pytest.raises((ZeroDivisionError, TypeError)): result = 'a' + 1 # raises TypeError
Sample Program
This test checks that risky_operation raises either ZeroDivisionError or TypeError for bad inputs. It also confirms normal input works.
PyTest
import pytest def risky_operation(value): if value == 0: raise ZeroDivisionError("Cannot divide by zero") elif not isinstance(value, int): raise TypeError("Value must be an integer") return 10 / value def test_risky_operation(): with pytest.raises((ZeroDivisionError, TypeError)): risky_operation(0) # should raise ZeroDivisionError with pytest.raises((ZeroDivisionError, TypeError)): risky_operation('a') # should raise TypeError # This call should NOT raise an exception assert risky_operation(2) == 5.0
OutputSuccess
Important Notes
Always use a tuple to list multiple exceptions inside pytest.raises().
If the code does not raise any of the listed exceptions, the test fails.
Use this to keep tests simple when multiple errors are acceptable.
Summary
Use pytest.raises() with a tuple to test multiple exceptions.
The test passes if any one of the exceptions is raised.
This helps verify your code handles different error cases properly.