0
0
PythonHow-ToBeginner · 3 min read

How to Test Exceptions in Python: Simple Guide

To test exceptions in Python, use a try-except block to catch errors manually or use unittest.TestCase.assertRaises() for automated tests. This lets you check if your code correctly raises expected exceptions.
📐

Syntax

There are two common ways to test exceptions in Python:

  • Using try-except: Wrap the code that may raise an exception inside a try block and catch the exception in the except block.
  • Using unittest's assertRaises: In unit tests, use assertRaises() to check if a specific exception is raised.

Syntax examples:

python
try:
    # code that may raise
    risky_function()
except SomeException:
    # handle or test exception
    pass

# Using unittest
import unittest

class TestExample(unittest.TestCase):
    def test_error(self):
        with self.assertRaises(SomeException):
            risky_function()
💻

Example

This example shows how to test if a function raises a ValueError using both try-except and unittest.

python
def divide(a, b):
    if b == 0:
        raise ValueError("Cannot divide by zero")
    return a / b

# Manual test with try-except
try:
    divide(10, 0)
except ValueError as e:
    print(f"Caught an error: {e}")

# Automated test with unittest
import unittest

class TestDivide(unittest.TestCase):
    def test_divide_by_zero(self):
        with self.assertRaises(ValueError):
            divide(10, 0)

if __name__ == "__main__":
    unittest.main(exit=False)
Output
Caught an error: Cannot divide by zero . ---------------------------------------------------------------------- Ran 1 test in 0.000s OK
⚠️

Common Pitfalls

Common mistakes when testing exceptions include:

  • Not specifying the exact exception type, which can hide other errors.
  • Using a bare except: that catches all exceptions, making debugging harder.
  • Not using assertRaises in unit tests, leading to less clear test failures.

Example of wrong and right ways:

python
# Wrong: catches all exceptions, hides bugs
try:
    divide(10, 0)
except:
    print("Error caught")

# Right: catch specific exception
try:
    divide(10, 0)
except ValueError:
    print("ValueError caught")
Output
Error caught ValueError caught
📊

Quick Reference

Tips for testing exceptions in Python:

  • Use try-except for quick manual checks.
  • Use unittest.TestCase.assertRaises() for clear, automated tests.
  • Always specify the exact exception type to catch.
  • Use with statement with assertRaises for concise tests.

Key Takeaways

Use try-except blocks to manually test if code raises exceptions.
In unit tests, prefer unittest's assertRaises to check for exceptions clearly.
Always catch specific exceptions, not all exceptions, to avoid hiding bugs.
Use the with statement with assertRaises for clean and readable tests.