In Python, you can use the raise
keyword to manually raise exceptions. This allows you to signal that an error or unusual condition has occurred in your program. Raising exceptions is especially useful when you want to enforce specific conditions or validations. In this article, we will explore the usage of the raise
keyword with practical examples.
The basic syntax for raising an exception is:
raise ExceptionType("Error message")
Here, ExceptionType
is the type of exception you want to raise (e.g., ValueError
, TypeError
, etc.), and the string message provides details about the exception.
You can raise a ValueError
when an invalid value is encountered in your program.
def validate_age(age): if age < 0: raise ValueError("Age cannot be negative") print(f"Valid age: {age}") try: validate_age(-5) except ValueError as e: print(f"Error: {e}")
In this example, the validate_age
function raises a ValueError
if the age is negative. The exception is caught and handled in the except
block.
A TypeError
can be raised if an argument of the wrong type is provided to a function.
def add_numbers(a, b): if not isinstance(a, (int, float)) or not isinstance(b, (int, float)): raise TypeError("Both arguments must be numbers") return a + b try: result = add_numbers(10, "20") except TypeError as e: print(f"Error: {e}")
In this example, the function raises a TypeError
when a non-numeric argument is provided.
You can define and raise your own custom exceptions by creating a new exception class.
class CustomError(Exception): pass def check_value(value): if value > 100: raise CustomError("Value exceeds the maximum limit of 100") print(f"Value is acceptable: {value}") try: check_value(150) except CustomError as e: print(f"Custom error: {e}")
In this example, a custom exception CustomError
is defined and raised when the value exceeds 100.
You can use the raise
keyword with the from
clause to raise an exception while preserving the original exception as its cause.
try: result = int("abc") except ValueError as original_error: raise RuntimeError("Failed to convert string to integer") from original_error
Here, a RuntimeError
is raised with the original ValueError
as its cause, providing additional context about the error.
Exceptions can be raised based on specific conditions in your program logic.
def withdraw(amount, balance): if amount > balance: raise Exception("Insufficient funds") balance -= amount print(f"Withdrawal successful. Remaining balance: {balance}") try: withdraw(200, 100) except Exception as e: print(f"Error: {e}")
In this example, the withdraw
function raises an exception if the withdrawal amount exceeds the account balance.
raise
keyword is used to trigger exceptions in Python.raise
with from
preserves the original exception's context.Raising exceptions with the raise
keyword is a powerful way to enforce conditions, signal errors, and make your code more robust. Whether you're raising built-in exceptions or custom ones, this feature helps you manage errors in a controlled and meaningful way.