Raising Exceptions in Python Using raise | Python tutorials on BeingSkilled

In Python, not only can you handle exceptions using try and except, but you can also raise exceptions manually using the raise keyword. This gives you the power to stop program execution when an error condition is met or enforce certain rules in your code.

In this tutorial, we’ll explore how to use raise effectively, the syntax for raising built-in and custom exceptions, and when you should use it.

1. Why Raise Exceptions?

  • To signal an error when your code logic detects invalid data or state
  • To enforce input validation
  • To make your programs more robust and easier to debug

2. Basic Syntax of raise

raise ExceptionType("Error message")

Example 1: Raising a ValueError

age = -5
if age < 0:
    raise ValueError("Age cannot be negative")

Output: ValueError: Age cannot be negative

3. Raising Built-in Exceptions

Example 2: Raising ZeroDivisionError

num = 0
if num == 0:
    raise ZeroDivisionError("Cannot divide by zero")

Example 3: Raising TypeError

value = "100"
if not isinstance(value, int):
    raise TypeError("Expected an integer value")

4. Using raise Inside try Blocks

You can use raise inside a try block to trigger exceptions based on conditions, and then catch them using except.

Example 4:

try:
    marks = -10
    if marks < 0:
        raise ValueError("Marks cannot be negative")
except ValueError as e:
    print("Caught an error:", e)

5. Re-Raising Exceptions

Sometimes you may want to catch an error temporarily and then re-raise it after logging or processing.

Example 5:

try:
    raise KeyError("Missing key")
except KeyError as e:
    print("Logging error:", e)
    raise  # Re-raises the same exception

6. Raising Custom Exceptions

You can define your own exception classes by inheriting from Exception.

Example 6: Custom Exception

class InvalidScoreError(Exception):
    pass

score = 200
if score > 100:
    raise InvalidScoreError("Score cannot exceed 100")

7. Summary Table

Usage Description Example
raise ValueError Manually trigger a value error raise ValueError("Invalid value")
raise TypeError Wrong data type provided raise TypeError("Must be an int")
raise CustomError User-defined exception raise MyError("Custom message")
raise Re-raise last exception raise

8. Final Thoughts

Using the raise statement allows you to be proactive in your error handling by signaling when something has gone wrong based on custom logic. It's a powerful tool for validation, testing, and writing more predictable code. Whether you're raising built-in exceptions or creating your own, mastering raise will make your programs more robust and professional.