Module 5 Lesson 8: Raising Custom Exceptions
You're the boss. Learn how to use the 'raise' keyword to stop your program when your own business rules are broken, even if Python doesn't think it's an error.
Module 5 Lesson 8: Raising Custom Exceptions
Sometimes, Python thinks everything is fine, but you know a mistake has been made. If a user tries to withdraw $200 when they only have $100, Python isn't going to crash—it will just subtract the numbers and give them a negative balance. To prevent this, we can Raise our own exceptions.
Lesson Overview
In this lesson, we will cover:
- The
raiseKeyword: Intentionally stopping the program. - Built-in vs. Custom Messages: Clarifying why the code stopped.
- Validation Patterns: Using exceptions to enforce rules.
- Creating Custom Exception Classes: Defining your own error types.
1. The raise Keyword
You can trigger any standard Python exception manually using the raise keyword.
age = int(input("Enter your age: "))
if age < 0:
raise ValueError("Age cannot be a negative number!")
print(f"You are {age} years old.")
2. Why Raise an Error?
It’s often better for a program to "Fail Fast" than to continue with incorrect data.
- Security: Stop a login if the password attempt limit is reached.
- Data Integrity: Stop a database update if a required field is missing.
- Safety: Stop a robotic arm if it moves outside its "safe" zone.
3. Creating Your Own Exceptions
You can create your own specialized error types by inheriting from the Exception class. This makes your code look much more professional.
class InsufficientFundsError(Exception):
"""Custom exception for bank accounts."""
pass
balance = 50
withdraw = 100
if withdraw > balance:
raise InsufficientFundsError(f"You tried to withdraw ${withdraw} but only have ${balance}.")
4. The "Fail Soon" Principle
The goal of raising exceptions isn't to crash your program for the user, but to signal to another part of your code (the try/except block) that something went wrong so it can handle it correctly.
Practice Exercise: The Password Validator
- Create a custom exception class named
WeakPasswordError. - Write a function
check_password(password)that checks if a password is at least 8 characters long. - If it's shorter than 8, raise a
WeakPasswordErrorwith a helpful message. - Wrap your function call in a
try-exceptblock to catch your custom error and print the message.
Quick Knowledge Check
- What keyword is used to manually trigger an exception?
- Why would you create a custom exception class instead of just using
ValueError? - What is the benefit of "Failing Fast"?
- Does
raiseautomatically stop the program if it's not inside atryblock?
Key Takeaways
raiseallows you to enforce your own rules.- Custom exceptions (inheriting from
Exception) make errors more descriptive. - Raising errors helps prevent "nonsense" data from entering your system.
- It is better to raise a clear error than to let a subtle bug cause damage later.
What’s Next?
We’ve seen try and except. But what if you have code that should run only if no error happened, or code that must run regardless of what happened? In Lesson 9, we’ll finish our error management toolkit with Finally and Else Blocks!