To manually throw/raise an exception in Python, use the raise
keyword. You can raise built-in exceptions or custom exceptions. Here’s how:
1. Basic Syntax
raise ExceptionType("Optional error message")
2. Raise a Built-in Exception
Example: Raise a ValueError
when invalid input is detected.
def calculate_square_root(x):
if x < 0:
raise ValueError("Input must be non-negative")
return x ** 0.5
try:
calculate_square_root(-5)
except ValueError as e:
print(f"Error: {e}") # Output: Error: Input must be non-negative
3. Raise a Custom Exception
Create a custom exception class (inherits from Exception
):
class InvalidEmailError(Exception):
"""Raised when an email format is invalid"""
pass
def validate_email(email):
if "@" not in email:
raise InvalidEmailError(f"Invalid email: {email}")
try:
validate_email("user.example.com")
except InvalidEmailError as e:
print(e) # Output: Invalid email: user.example.com
4. Re-raise an Exception
Capture an exception and re-raise it (e.g., for logging):
try:
# Code that might fail
x = 1 / 0
except ZeroDivisionError:
print("Logging the error...")
raise # Re-raise the same exception
5. Raise Without Specifying an Exception
Not recommended, but possible (raises a generic RuntimeError
):
if error_condition:
raise # ❌ Avoid: Only works inside an except block
Common Built-in Exceptions
Exception Type | Use Case | Example |
---|---|---|
ValueError | Invalid value for a function | raise ValueError("Invalid input") |
TypeError | Incorrect type passed to a function | raise TypeError("Expected str") |
FileNotFoundError | File/directory not found | raise FileNotFoundError("Missing file") |
KeyError | Missing dictionary key | raise KeyError("Key not found") |
RuntimeError | Generic error for unexpected conditions | raise RuntimeError("Unexpected state") |
Best Practices
- Use specific exceptions (e.g.,
ValueError
instead of genericException
). - Include meaningful messages to clarify the error.
- Create custom exceptions for domain-specific errors.
By raising exceptions, you can enforce constraints and improve error handling in your code.