Raising Custom Exceptions
Sometimes, you need to stop execution deliberately because a condition that makes the program unstable or illogical has been met. The raise statement allows you to trigger an exception manually.
Using raise with Built-in Exceptions
You can raise standard Python exceptions and provide a message explaining why.
python def check_age(age): if not isinstance(age, int): raise TypeError("Age must be an integer.") if age < 0: raise ValueError("Age cannot be negative.") print("Age check passed.")
try: check_age(-5) except ValueError as e: print(f"Error caught: {e}")
Output: Error caught: Age cannot be negative.
When to Raise an Exception
- When a function receives invalid arguments (like the
check_ageexample). - When required external resources (like files or network connections) are unavailable.
- When logic fails spectacularly (e.g., data corruption detected).
Raising exceptions is crucial for creating robust functions that clearly signal failure states to the calling code.