In Python, exceptions can be raised manually using the raise
statement. This allows you to throw an exception when a specific condition is met, such as invalid input, business logic errors, or when a function cannot proceed as expected.
What is Raising an Exception?
Raising an exception refers to explicitly triggering an exception during the program’s execution using the raise
statement. When an exception is raised, the normal flow of the program is interrupted, and the program looks for an except
block to handle the error.
Basic Syntax of Raising an Exception
The syntax for raising an exception is:
raise ExceptionType("Error message")
1. Raising a Built-in Exception
You can raise any built-in exception in Python, such as ValueError
, TypeError
, or IndexError
, by using the raise
statement.
Example:
def divide(a, b): if b == 0: raise ZeroDivisionError("Error: Cannot divide by zero.") return a / b try: result = divide(10, 0) except ZeroDivisionError as e: print(e)
In this example, we raise a ZeroDivisionError
manually when the user attempts to divide by zero. The exception is caught in the except
block, and an appropriate error message is printed.
2. Raising a Custom Exception
In addition to raising built-in exceptions, you can also create and raise your own custom exceptions. This is useful for handling domain-specific errors in your applications.
Example:
class CustomError(Exception): def __init__(self, message): self.message = message super().__init__(self.message) def validate_age(age): if age < 18: raise CustomError("Error: Age must be 18 or older.") return f"Age {age} is valid." try: print(validate_age(16)) except CustomError as e: print(e)
Here, we define a custom exception CustomError
and raise it if the user provides an age less than 18. This allows for more specific error handling and messaging in your code.
3. Raising an Exception with the raise Keyword Without Specifying Exception Type
You can also raise the last exception encountered using the raise
keyword without specifying the exception type. This is useful when you want to propagate the current exception.
Example:
def handle_error(): try: raise ValueError("A value error occurred.") except ValueError as e: print(f"Handling error: {e}") raise # Re-raises the last exception try: handle_error() except ValueError as e: print(f"Caught re-raised exception: {e}")
In this example, we catch the exception in the except
block, print a message, and then re-raise the exception using raise
without specifying the exception type again.
4. Raising an Exception with a Custom Message
You can also provide custom messages when raising an exception to provide additional context for debugging.
Example:
def check_value(x): if x < 10: raise ValueError(f"Error: {x} is less than the minimum allowed value of 10.") return f"Value {x} is valid." try: print(check_value(5)) except ValueError as e: print(e)
In this example, we raise a ValueError
with a custom message to indicate that the provided value is less than the allowed minimum.
5. Raising Exceptions in Functions and Methods
Raising exceptions can be used in functions and methods to prevent further execution when a condition is violated.
Example:
def withdraw(amount, balance): if amount > balance: raise ValueError("Insufficient funds.") return balance - amount try: print(withdraw(100, 50)) except ValueError as e: print(e)
Here, we raise a ValueError
if the withdrawal amount exceeds the available balance. This prevents the function from continuing and ensures that the operation is safe.
Conclusion
Raising exceptions in Python allows you to proactively handle specific error conditions and manage your program flow effectively.