Course contentsShow
← Python
Lesson 345 of 1,0606. Error Handling and File I/OFree lesson

Raising Custom Exceptions Manually

Trigger your own exceptions using the raise keyword to enforce application-specific business rules and signal invalid states to the caller.

In this lesson, you will learn how to proactively trigger your own errors to enforce specific rules in your code.

Why Raise Exceptions?

So far, you’ve learned how to try and except errors that Python throws automatically, like ValueError or ZeroDivisionError. However, sometimes your application has its own "business rules." For example, if you are writing a banking program, you might want to ensure a user never withdraws more money than they have.

Python doesn’t know what a "bank balance" is, so it won’t throw an error if you set an account to negative. You have to manually signal that something is wrong. We use the raise keyword for this.

Manually Triggering an Error

When you raise an exception, you effectively pause the current execution flow and pass an error object up to the caller, just like the system does when a runtime exception occurs.

def withdraw_money(balance, amount):
    if amount > balance:
        # We manually trigger an exception if the rule is violated
        raise ValueError("Insufficient funds: You cannot withdraw more than your balance.")
    
    return balance - amount

try:
    current_balance = 50
    new_balance = withdraw_money(current_balance, 100)
except ValueError as e:
    print(f"Transaction failed: {e}")

How It Works

  1. The Check: You define a condition that represents an "invalid state" for your specific logic.
  2. The Raise: You use the raise keyword followed by an exception type (like ValueError) and a descriptive string.
  3. The Interruption: As soon as raise is hit, the rest of the code in that function stops, and the error travels up the stack until it is caught by an except block.

By doing this, you keep your code clean and your logic safe. Instead of letting the program continue with bad data, you stop it immediately and provide a helpful message about what went wrong.

Key Takeaway: Use the raise keyword to interrupt your program whenever your custom business logic is violated, allowing your except blocks to handle the recovery cleanly.