Files & Error Handling

Raising Exceptions

You can create your own errors using

raise
.

Basic Raise

def check_age(age):
    if age < 0:
        raise ValueError("Age cannot be negative!")
    return f"Age is {age}"

When to Raise Exceptions

  • Invalid input that your function can't handle
  • Unexpected conditions that need attention
  • To enforce rules in your code

Custom Error Messages

def withdraw(amount, balance):
    if amount > balance:
        raise ValueError(
            f"Insufficient funds! Balance: {balance}, Requested: {amount}"
        )
    return balance - amount

Catching Your Own Exceptions

try:
    check_age(-5)
except ValueError as e:
    print(f"Error: {e}")
Visualizer
$ python validate.py
Invalid: Username must be at least 3 characters Username is valid!

Interactive Visualization

python
Loading...
Output
Run execution to see output...