The raise keyword in Python is used to manually trigger an exception. It allows you to signal that something unexpected has occurred in the program, and provide an appropriate error message or custom exception.
Example
age = -5
if age < 0:
raise ValueError("Age cannot be negative")
Output:
Traceback (most recent call last):
...
ValueError: Age cannot be negative
Syntax
raise ExceptionType("Error message")
- ExceptionType: The type of exception to raise (e.g., ValueError, TypeError, RuntimeError, etc.).
- Error message: A custom message describing the error (optional).
You can also re-raise an existing exception:
raise
Why Use raise?
- Error Handling: Signal when something goes wrong and provide meaningful error messages.
- Input Validation: Ensure input or data meets certain conditions, and raise an exception otherwise.
- Custom Exceptions: Define and trigger custom exceptions for domain-specific errors.
Common Examples
1. Raising a Built-in Exception
x = -1
if x < 0:
raise ValueError("x cannot be negative")
Output:
Traceback (most recent call last):
...
ValueError: x cannot be negative
2. Raising a Custom Exception
class CustomError(Exception):
pass
def check_value(value):
if value > 100:
raise CustomError("Value exceeds the limit")
check_value(150)
Output:
Traceback (most recent call last):
...
__main__.CustomError: Value exceeds the limit
3. Re-raising an Exception
try:
raise ValueError("Initial error")
except ValueError as e:
print("Handling the exception...")
raise # Re-raise the same exception
Output:
Handling the exception...
Traceback (most recent call last):
...
ValueError: Initial error
4. Raising Exceptions in Functions
def divide(a, b):
if b == 0:
raise ZeroDivisionError("Division by zero is not allowed")
return a / b
print(divide(10, 0))
Output:
Traceback (most recent call last):
...
ZeroDivisionError: Division by zero is not allowed
5. Validating User Input
def set_age(age):
if age < 0:
raise ValueError("Age must be a positive number")
print(f"Age set to {age}")
set_age(-5)
Output:
Traceback (most recent call last):
...
ValueError: Age must be a positive number