Python

Python Create Custom Exceptions

While working in any programming environment, you may have encountered several errors when something goes wrong with your code. Those exceptions that occur automatically by the interpreter or compiler are said to be built-in exceptions. Just like built-in exceptions, some programming languages provide us the ability to create custom exceptions according to our needs. Have you ever tried to create your exceptions within the try-catch block of code in object-oriented programming? Within this article, we will be discussing a simple method to create custom exceptions in Python. Let’s start with the launch of the terminal application from the activity area of Linux by utilizing the simple shortcut “Ctrl+Alt+T”. You have to install Python’s latest version and you are good to go.

After the Python installation, we need a Python file to make codes. For this, we will be using the “touch” keyword in the query area and the filename for a file to be created. Execute this command and the file will be generated in the current “home” directory. After that, try opening your new file with any built-in editor of Ubuntu 20.04 i.e., we are opening it within Nano editor.

Example 01:

The empty file will be launched and ready for your use. Firstly, we will be taking a look at the built-in Python exceptions. For this, we have added the python-support “#!/usr/bin/python” at the first line and created a new class “test”. The class contains a variable “x” with some value. Take a good look at the value of “x” as it contains the single quote in between that will cause an error. We have created an object “t” for the class test using the standard method. This newly made object “t” has been used to call the variable “x” via the “dot” method. This has been done in the print statement to display the value of “x”.

The Python “custom.py” file that has just been updated with the code, has been executed in the Python pool. We have got the exception “SyntaxError: EOL while scanning string literal” after running this code. The error is indicating that the error is caused due to the value of “x”.

Now, we will be taking a look at the simplest way to create custom exceptions using our Python code. So, start the same custom.py file in the GNU Nano editor with the execution of a “nano” instruction at the shell query area. Added the python-support “#!/usr/bin/python” at the first line of this file. Initialized a new class named “CustomException” that has been derived from the built-in Exception class as we have been implementing the “Exception” class in its parameter. This means our newly generated class will implement the Exception class to generate a custom exception of our choice.

The “pass” keyword has been used to simply avoid the complex code and get towards the next step to generate an exception. The keyword “raise” has been used to generate an exception and call the newly made class “CustomException” deriving from the “Exception” class. The “raise” keyword line will generate an error on execution showing the line number and the main() function at the output. Let’s save this code first and exit the file using Ctrl+S and Ctrl+X.

On running the updated Python file “custom.py”, we have got the error “__main__.CustomException”. As we haven’t used any statement in the class, that’s why it generates a simple output for an exception without any exception explanation message.

Example 02:

Let’s dive a little deeper into the concept of creating custom exceptions in Python. The first example was used to display the most simple syntax of creating custom exceptions in Python. Now, we will be creating custom exceptions with some errors explaining the message along with some conditions. We have opened the file and declared three new classes: Err, SmallException, and LargeException.The Err class is derived from the built-in Exception class while the other two classes are derived from the “Err” class.

Initialize a variable “x” with value 4 and used the try-except block in the code. The “Try” block is taking integer input from a user via the “input” function and saves it to a variable “n”. The nested “if-else” statement is here to compare the value of variable “n” with the value of variable “x”. If the value “n” is less than value “x”, it will raise SmallException using the raise keyword along with the class name “SmallException”. If the value “n” is greater than value “x”, it will raise LargeException using the class name “LargeException”. If both the conditions don’t meet, we will go with the display of a simple message on the shell using the print statement i.e., “Value is equal”.

After the “try” block, we have been using 2 except parts to raise the error messages according to the condition. If the value is less than the mentioned ones, the “SmallException” exception will be triggered otherwise the LargeException will be executed. The print statement within both except parts is utilizing the string message according to their need i.e., small and large.

On execution, our user has added value 8 i.e., greater than value x = 4. The LargeException has been executed. On running again, the user added the small value 2 and got the SmallException executed. At last, the user added the equal value the success message is shown.

If you want to try adding the input from the user until the desired one, you can make use of the “while” loop as we did beneath.

Now, the output will be something like below.

Example 03:

There is another way to create custom exceptions in Python and that is the use of the “__init__” and “__str__” function of Python. The “__init__” is said to be the constructor of a class that will be used to initialize values. We have created an exception class “Err” implementing the built-in “Exception” class in this Python code.

Taking two arguments, it will initialize the value of variable “age” and “msg” with the key object “self”. The “Exception” superclass “__init__” constructor function has been called using the “super()” and passed the “msg” variable in its parameter. The “__str__” method is used to display the “error” message according to the string format shown in its return statement.

The “age” variable is taking number value from the user via the “input” function and the string variable “msg” is initialized. The “if-else” statement is here to raise a custom exception when the value “age” is less than 20 and greater than 50. Else, the “else” part will display the success message.

On the first execution, the user added 40 and got the success message i.e., 40 > 20, and 40 < 50.

On the second execution, the user added 80 as input age i.e., 80 is greater than 50. We have got the exception in the same format as we have declared in the “__str” function.

Conclusion

This was all about making custom exceptions in our Python environment wherever required. We have discussed quite the simplest way possible to make it easy for our users i.e., starting examples from the most basic syntax. We have also discovered the use of “__init__”, and “__str__” functions used in the creation of custom exceptions. This was all quite easy to implement.

About the author

Aqsa Yasin

I am a self-motivated information technology professional with a passion for writing. I am a technical writer and love to write for all Linux flavors and Windows.