Create Python Custom Exceptions [SOLVED]

With the support of examples, you will learn in this training how to design unique exceptions based on your needs. Python comes with a variety of built-in exceptions that require your code to print an error whenever something goes wrong. But occasionally you might need to make your own special and custom exceptions that are tailored to your needs. We will be doing some useful examples to implement custom exceptions using Python.

class CustomError(Exception):
    pass
raise CustomError("Simple Example of Custom Exceptions in Python")

When something goes wrong in the code, Python raises errors and exceptions, which might result in abrupt program termination. With the aid of try-except, Python additionally provides an exception-handling technique. IndexError, ImportError, IOError, ZeroDivisionError, TypeError, and FileNotFoundError are some of the common standard exceptions. These are all the built-in exceptions that come along with python. Studying the built-in exceptions is not in the scope of this article.

Advertisement

We will focus on the custom exceptions in Python.

 

Create user-defined custom exception in Python

Exceptions must be directly or indirectly descended from the Exception class. Even though it's not required, most exceptions have names that finish in "Error," just like Python's default exceptions.

Create Python Custom Exceptions [SOLVED]

As we can see in the above figure, we inherit the custom exception class from the exception class. Let’s have a look at the following example which defines a custom exception that is inherited from the exception class in Python.

class CustomException(Exception):
    """ Custom Exception class inherited from Exception class """
NOTE:

Take note of the docstring that the CustomException class contains since it functions as a statement. Therefore, the pass statement is not required to make the syntax legitimate.

Now, to raise a custom exception, we use a raise statement. Let's see the following example by extending the above code snippet and adding the raise statement to it.

class CustomException(Exception):
    """ Custom Exception class inherited from Exception class """
try:
    raise CustomException('My Custom Exception')
except for CustomException as ex:
    print(ex)

As you can see in the code snippet above, we have defined a class called CustomException which is inherited from the Exception class. Now to raise our custom exception, we have to use the try-except statement. Try-except statement is used when we want to try something and if there is a problem or an error with the code we write, it will be caught in the catch statement. In the above example, we are raising a custom exception in the try statement, and the custom error will be caught in the except statement. We will see this in detail by looking at some examples ahead. The output of the above code is shown below.

Advertisement

Output:

My Custom Exception

 

Custom exception examples in Python

To understand the custom exception class, let’s look at some examples which will explain the idea of exception and custom exception very well.

 

Example 1:

In this example, we are going to make a custom exception class, we will call it dobException. We want to design a Python program that will take the age of the user, and after that, some conditions will be applied like if the person's age is above 20 and less than 30, He/She is eligible to apply for the job otherwise the program will through a custom exception message that the person is not eligible to apply for the job. The idea is simple, let's achieve this.

class dobException(Exception):
    pass

We have defined a class and named it dobException which is inherited from the Exception class.

year=int(input("Enter your DOB: "))
age=2022-year
try:
    if age<=30 & age>20:
        print("The age is valid. You can apply for the job")
    else:
        raise dobException
except dobException:
    print("The age is not within the range. You cannot apply for the job")

In the above code snippet, we are taking the date of birth from the user, when the date of birth is entered, we are calculating the current age of the user by subtracting the date of a birth year from the current year. After that, we have enclosed the if-condition in the try-except statement. The try statement will try to match the entered age with the conditions specified by us, if the condition is true then the program be terminated in the try statement by giving the output that you are eligible for the job. If the age is less than 20 or greater than 30 then the program will jump into the except statement and our custom exception class will be called there with our custom message.

Output:

Advertisement
Enter your DOB: 1998
The age is valid. You can apply for the job

The user has entered the DOB as 1998, the program will calculate the age by subtracting the DOB entered from the current year. In our case, it is 2022-1998 which is equal to 24 years. The program will show a message that you are eligible for the job.

Enter your DOB: 1975
The age is not within the range. You cannot apply for the job

Another user has entered their DOB which is 1975, the age of the user is 2022-1975 which is equal to 47 years. In this case, the dobException class will be called in the except statement and our custom exception message will show. Let’s see another example.

 

Example 2:

In this example, we are inheriting our custom exception class from a base class named Error. The goal is to make a program that will take a number from the user, if the number is zero then the program will go into our custom-made exception, otherwise, it will print the number. Let’s look at the code below.

class Error(Exception):
    pass
class zerodivision(Error):
    pass
try:
    i_num = int(input("Enter a number: "))
    print('The number is not zero :  ', i_num)
    if i_num == 0:
        raise zerodivision
except zerodivision:
    print("Input value is zero, try again!")
    print()

We have defined a class called Error which is inherited from the Exception class. Then we defined our custom exception class named zerodivision which is inherited from our base class Error, In the try section, we are taking a number from the user, then a condition is applied, if the number is equal is to zero then the try statement will our custom exception message, otherwise, the number will be printed. Let’s run the above code.

Output:

Enter a number: 0
The number is not zero :   0
Input value is zero, try again!

The number entered is zero and the program throws our custom build exception.

 

Advertisement

Example 3:

Let’s go into something different and in detail now. Let's say a bank has a policy that if the balance is less than or equal to 2000 then the customers cannot withdraw money. In this example, the current balance is taken as 30000, and the customer wants to withdraw some money from the bank. If the customer wants to withdraw 29000 from the bank then the code will through our custom-made exception. let's look at the code below to understand it more clearly.

# class inherited from Exception 
class BankBalanceException(Exception):
    pass
# function to check the current balance
def check_current_balance():
    money = 30000
    withdraw = int(input('How much you want to withdraw?: '))
    current_balance = money - withdraw
# if the balance is less or equal to 2000
# bank will not withdraw the money
    if(current_balance<=2000):
        raise BankBalanceException('Insufficient balance')
    print(current_balance)

try:
    check_current_balance()
except BankBalanceException as BBE:
    print(BBE)

We have a class named BankBalanceException(Exception)which is inherited from the Exception class. We have a function check_current_balance()that will take the amount of money the customer wants to withdraw, this function will also check if the balance after the withdrawal is less than or equal to 2000. If yes, the code will immediately through our custom exception, else the amount will be withdrawn successfully. let's give it a run.

Output:

How much you want to withdraw?: 29000
Insufficient balance

The customer wants to withdraw 29000 from the bank, the current balance is 30000. The amount after this withdrawal will be equal to 2000 which is not acceptable by the bank, so the code has thrown our custom exception.

How much you want to withdraw?: 20000
10000

In the above case, the customer wants to withdraw 20000 and the remaining balance will be 10000, so the withdrawal is successful and the remaining balance is shown by our code. That's the beauty of custom exception. That's all for today. Stay connected to this platform.

Thank You!

 

Advertisement

Summary

We have seen today to create a unique exception class, subclass the Exception class or one of its subclasses. We have also studied how to structure the exception classes and catch exceptions at various levels, creating an exception class hierarchy. we have seen three examples that explain the idea of custom exception very well.

 

Further Reading

User-defined Exceptions

 

Didn't find what you were looking for? Perform a quick search across GoLinuxCloud

If my articles on GoLinuxCloud has helped you, kindly consider buying me a coffee as a token of appreciation.

Buy GoLinuxCloud a Coffee

For any other feedbacks or questions you can either use the comments section or contact me form.

Thank You for your support!!

Leave a Comment

X