raise and Custom Exceptions
Why raise exceptions?
You can use raiseraise to:
- validate function inputs
- enforce rules
- stop invalid workflows early
raise_example.py
def set_age(age: int) -> int:
if age < 0:
raise ValueError("age must be >= 0")
return age
print(set_age(10))
# print(set_age(-1))raise_example.py
def set_age(age: int) -> int:
if age < 0:
raise ValueError("age must be >= 0")
return age
print(set_age(10))
# print(set_age(-1))Raise with a custom message
raise_message.py
score = -5
if score < 0:
raise ValueError(f"score must be non-negative, got {score}")raise_message.py
score = -5
if score < 0:
raise ValueError(f"score must be non-negative, got {score}")Creating custom exceptions
Custom exceptions help you represent domain-specific errors.
custom_exception.py
class PaymentError(Exception):
"""Raised when a payment fails."""
def charge(amount: float) -> None:
if amount <= 0:
raise PaymentError("Amount must be positive")
try:
charge(0)
except PaymentError as e:
print("Payment failed:", e)custom_exception.py
class PaymentError(Exception):
"""Raised when a payment fails."""
def charge(amount: float) -> None:
if amount <= 0:
raise PaymentError("Amount must be positive")
try:
charge(0)
except PaymentError as e:
print("Payment failed:", e)Re-raising exceptions
Sometimes you want to log something and re-raise.
reraise.py
try:
int("abc")
except ValueError as e:
print("Logging error:", e)
raisereraise.py
try:
int("abc")
except ValueError as e:
print("Logging error:", e)
raiseBest practices
- Donβt leak secrets in error messages.
- Use clear messages: what went wrong + what to do.
- Prefer built-in exception types when they fit.
π§ͺ Try It Yourself
Exercise 1 β Raise a Built-in Exception
Exercise 2 β Define a Custom Exception
Exercise 3 β Re-raise an Exception
If this helped you, consider buying me a coffee β
Buy me a coffeeWas this page helpful?
Let us know how we did
