DEV Community

Cover image for Day 19/100: Assertions and Raising Custom Errors in Python
 Rahul Gupta
Rahul Gupta

Posted on

Day 19/100: Assertions and Raising Custom Errors in Python

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)"
Enter fullscreen mode Exit fullscreen mode

πŸ§ͺ Example 1: Simple Assertion

age = 20
assert age >= 18, "You must be at least 18"
print("Access granted!")
Enter fullscreen mode Exit fullscreen mode

If age = 16, you'll see:

AssertionError: You must be at least 18
Enter fullscreen mode Exit fullscreen mode

πŸ€” 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.")
Enter fullscreen mode Exit fullscreen mode

This stops the program and shows:

ValueError: Age cannot be negative.
Enter fullscreen mode Exit fullscreen mode

πŸ› οΈ 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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

🧠 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)