Welcome to Day 19 of the 100 Days of Python series!
Today, we go deeper into error handling by learning about two powerful tools Python gives us:
- ✅
assertstatements for debugging - 🔥
raisekeyword for creating custom errors
These tools help us catch bugs early, write self-validating code, and handle invalid input cleanly — especially in bigger programs or APIs.
Let’s dive in! 🐍
📦 What You’ll Learn
- What assertions are and how to use them
- When to use
assertvs exceptions - How to raise built-in and custom exceptions
- Real-world examples
- Best practices
✅ 1. What is an assert?
An assert is a debugging aid that tests whether a condition is True.
If the condition is False, it raises an AssertionError and stops the program.
🔹 Syntax:
assert condition, "Error message (optional)"
🧪 Example 1: Simple Assertion
age = 20
assert age >= 18, "You must be at least 18"
print("Access granted!")
If age = 16, you'll see:
AssertionError: You must be at least 18
🤔 When to Use assert
- When you want to check for conditions that must always be true
- Useful during development and debugging
- Not meant for user input validation (use exceptions instead)
✅ Good for catching internal logic errors early
🔥 2. Raising Errors with raise
The raise keyword lets you manually trigger an exception when a condition is not met.
🔹 Example: Raising a built-in error
age = -5
if age < 0:
raise ValueError("Age cannot be negative.")
This stops the program and shows:
ValueError: Age cannot be negative.
🛠️ 3. Creating Custom Exceptions
You can define your own error classes by extending Python’s Exception class.
🔹 Example:
class TooYoungError(Exception):
pass
def check_age(age):
if age < 18:
raise TooYoungError("You must be at least 18 years old.")
check_age(16) # Raises TooYoungError
Custom exceptions are useful when your app has specific rules — like minimum order amount, login limits, or age verification.
🚀 Real-World Example: Bank Withdrawal
class InsufficientFundsError(Exception):
pass
def withdraw(balance, amount):
if amount > balance:
raise InsufficientFundsError("Not enough balance.")
return balance - amount
print(withdraw(1000, 1200)) # Raises error
🧠 Assertions vs Raise: Key Differences
| Feature | assert |
raise |
|---|---|---|
| Use case | Debugging, internal checks | Validating inputs, real errors |
| Runtime usage | Often removed in production | Used in production |
| Exception type | Always raises AssertionError
|
Can raise any type |
| Message | Optional, string only | Custom messages & types |
📌 Best Practices
- ✅ Use
assertfor internal, development-time checks - ✅ Use
raisefor user-facing or expected error situations - ❌ Don’t rely on
assertfor input validation - ✅ Create custom exceptions to handle business logic cleanly
- 🧼 Keep error messages clear and useful
🧠 Recap
Today you learned:
- How to use
assertto validate assumptions during development - How to use
raiseto throw built-in or custom exceptions - How to define and use your own exception classes
- Real-world examples for business logic and error reporting
Top comments (0)