How to Create User Defined Exceptions in Python?
User-defined exceptions in Python are custom exceptions that you create yourself to handle specific situations in your code. These exceptions are created by creating a new class that inherits from the built-in Exception class. You can define your own error messages and raise these exceptions when necessary, which can then be caught and handled in a try-except block.
By creating your own custom exceptions, you can have more control over the error handling in your code. This makes it easier to identify and diagnose issues, and can also make your code more readable and maintainable.
For example, you might create a custom exception to handle situations where a user tries to access a resource that they don't have permission to access, or if an invalid argument is passed to a function. These custom exceptions can then be raised and caught in the appropriate part of your code, allowing you to provide a clear and specific response to the user or to handle the error in a controlled manner.
Once you have defined your custom exception class, you can raise it in your code using the raise keyword:
class MyException(Exception):
pass
raise MyException("This is a custom exception")
In this example, MyException is a custom exception class that inherits from Exception. To raise an exception, use the raise keyword and pass an instance of your custom exception class to it, along with an error message.
You can also catch the exception using a try...except block:
try:
raise CustomException("This is a custom exception")
except CustomException as e:
print(e.message)
In this example, the try...except block catches the CustomException and stores it in the e variable. The error message can then be displayed using the e.message attribute.
By creating custom exceptions, you can better handle specific errors in your code and provide more meaningful error messages to the user.
Here is an example of creating a user-defined exception in Python:
Example:
class InsufficientBalanceException(Exception):
def __init__(self, message):
self.message = message
def withdraw_money(balance, amount_to_withdraw):
if balance <amount_to_withdraw:
raise InsufficientBalanceException("You have insufficient balance to withdraw this amount.")
else:
balance -= amount_to_withdraw
print("Withdrawn amount: ", amount_to_withdraw)
print("Current balance: ", balance)
try:
withdraw_money(1000, 2000)
except InsufficientBalanceException as error:
print(error)
Output:
You have insufficient balance to withdraw this amount.
In this example, we have defined a custom exception called InsufficientBalanceException which inherits from the built-in Exception class. Then, we have a function withdraw_money which raises the custom exception if the balance is less than the amount to be withdrawn. Finally, we use a try-except block to catch the exception and print the error message.
Deriving an Exception Class
To derive an exception class in Python, you need to create a new class that inherits from the built-in Exception class. Here is an example of how to do this:
class MyException(Exception):
def __init__(self, message):
self.message = message
In this example, we have created a new class MyException that inherits from the Exception class. The __init__ method is a special method that is called when an object of the class is created. In this case, we're passing an argument message and storing it as an instance variable self.message.
Once you have defined your custom exception class, you can raise an exception by calling the raise statement and passing an instance of the custom exception class to it:
raiseMyException("This is a custom exception")
Finally, you can catch the exception in a try-except block:
try:
# code that may raise the exception
except MyException as error:
# code to handle the exception
print(error.message)
In this example, the try block contains the code that may raise the exception, and the except block contains the code that will be executed if the exception is raised. The error variable holds the instance of the custom exception class, and we can access the error message using error.message.
Here is an example of deriving an exception class in Python:
Example:
class NegativeAgeException(Exception):
def __init__(self, message):
self.message = message
def set_age(age):
if age < 0:
raise NegativeAgeException("Age cannot be negative.")
print("Age set to: ", age)
try:
set_age(-30)
except NegativeAgeException as error:
print(error.message)
Output:
Age cannot be negative.
In this example, we've defined a custom exception class NegativeAgeException that inherits from the built-in Exception class. The __init__ method takes an argument message and stores it as an instance variable self.message. Then, we have a function set_age which raises the custom exception if the age is negative. Finally, we use a try-except block to catch the exception and print the error message stored in error.message.