Python > Core Python Basics > Error Handling > Raising Exceptions (raise keyword)
Raising Custom Exceptions in Python
This snippet demonstrates how to raise custom exceptions in Python using the raise
keyword. It also covers defining custom exception classes that inherit from the base Exception
class. Understanding exception handling is crucial for writing robust and maintainable Python code.
Basic Example: Raising a Built-in Exception
This code defines a function check_age
that raises a ValueError
if the age is negative. The try...except
block catches the exception and prints an error message. This illustrates the basic use of the raise
keyword with a built-in exception type.
def check_age(age):
if age < 0:
raise ValueError("Age cannot be negative")
else:
print("Age is valid.")
try:
check_age(-5)
except ValueError as e:
print(f"Error: {e}")
check_age(25)
Creating a Custom Exception Class
This example demonstrates how to define a custom exception class called InsufficientFundsError
that inherits from the base Exception
class. It overrides the __init__
method to accept a custom error message. The withdraw
function now raises this custom exception when the withdrawal amount exceeds the balance. The try...except
block catches the custom exception.
class InsufficientFundsError(Exception):
def __init__(self, message):
self.message = message
super().__init__(self.message)
def withdraw(balance, amount):
if amount > balance:
raise InsufficientFundsError("Insufficient funds in your account")
else:
print("Withdrawal successful.")
return balance - amount
balance = 100
try:
new_balance = withdraw(balance, 150)
print(f"New balance: {new_balance}")
except InsufficientFundsError as e:
print(f"Error: {e}")
Explanation of raise
keyword
The raise
keyword is used to explicitly raise an exception in Python. It allows you to signal that an error or unexpected condition has occurred during the execution of your code. You can raise built-in exceptions or create your own custom exceptions.
Real-Life Use Case Section
Imagine building an e-commerce platform. You might want to raise a ProductOutOfStockError
if a customer tries to purchase a product that is no longer available. Similarly, a InvalidCouponCodeError
could be raised if a user enters an incorrect coupon code. Raising exceptions allows your code to handle such situations gracefully and inform the user about the problem.
Best Practices
Exception
unless you have a very good reason. Catch only the specific exceptions you expect and know how to handle.try...finally
blocks to ensure that resources (like files or network connections) are properly cleaned up, even if an exception occurs.
Interview Tip
During interviews, be prepared to discuss exception handling best practices, including when to use custom exceptions and how to write effective try...except
blocks. Demonstrate your understanding of the different types of exceptions and how to handle them gracefully.
When to Use Them
Use exceptions when your code encounters an error condition that it cannot handle itself. This allows the calling code to take appropriate action, such as logging the error, retrying the operation, or informing the user.
Alternatives
While exceptions are the preferred method for handling errors in Python, alternative approaches include returning error codes or using special return values to indicate failure. However, these methods can be less readable and harder to maintain compared to using exceptions, especially for complex error scenarios.
Pros
Cons
FAQ
-
What is the difference between
Exception
andBaseException
?
Exception
is the base class for all built-in, non-system-exiting exceptions.BaseException
is the base class for all exceptions, includingSystemExit
,KeyboardInterrupt
, andGeneratorExit
. You should typically inherit fromException
when creating custom exception classes. -
How do I re-raise an exception?
You can re-raise an exception using theraise
keyword without any arguments inside anexcept
block. This will re-raise the exception that was caught, allowing it to be handled by a higher-leveltry...except
block.