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:
- β
assert
statements for debugging - π₯
raise
keyword 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
assert
vs 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
assert
for internal, development-time checks - β
Use
raise
for user-facing or expected error situations - β Donβt rely on
assert
for input validation - β Create custom exceptions to handle business logic cleanly
- π§Ό Keep error messages clear and useful
π§ Recap
Today you learned:
- How to use
assert
to validate assumptions during development - How to use
raise
to 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)