Python raise Statement Raise an Exception
The raise
statement in Python is used to trigger exceptions manually, allowing you to enforce certain conditions or handle errors more explicitly in your code.
Basic Syntax
raise ExceptionType("Optional error message")
You can raise any built-in or custom exception using this.
Example 1: Raise a Built-in Exception
x = -5
if x < 0:
raise ValueError("x cannot be negative")
Output:
ValueError: x cannot be negative
Explanation:
- This raises a
ValueError
ifx
is negative. - Useful for enforcing input validation.
Example 2: Raising TypeError
x = "5"
if not isinstance(x, int):
raise TypeError("Expected an integer")
Output:
TypeError: Expected an integer
Explanation:
- This checks if the input is an integer.
- If not, it raises a
TypeError
.
Example 3: Using raise
Without an Argument (Inside except
)
try:
raise ValueError("Initial error")
except ValueError as e:
print("Caught:", e)
raise # Re-raise the exception
Output:
Caught: Initial error
Traceback (most recent call last):
...
ValueError: Initial error
Explanation:
- You can re-raise the same exception to propagate it further.
- This is useful in exception logging or when you want to handle and forward an error.
Raising Custom Exceptions
You can also define your own exceptions by creating a custom class:
class MyCustomError(Exception):
pass
def validate(age):
if age < 18:
raise MyCustomError("You must be 18 or older.")
validate(15)
Output:
MyCustomError: You must be 18 or older.
When to Use raise
- Input validation
- Enforcing rules (e.g., login must not be empty)
- Creating custom domain-specific exceptions
- Propagating lower-level exceptions in higher-level logic