Customizing Exceptions in Python

Tram Ho

Hello everyone in this article, I will introduce to you how to customize the Exceptions in Python, I will explain to you how to understand and how to use them. You can find out in my article!


In this article I will guide you on how to customize the Exceptions according to your personal wishes. I will give you examples to make it easier to understand.

There are lots of built-in Exceptions available in Python, but sometimes you still need to create your own Exceptions for your purposes.


Create custom Exceptions

In Python, users can define custom Exceptions by creating new Exceptions . Exceptions newly created Exceptions must be derived from the existing Exceptions of the system.

In the above example. I have created 1 Exceptions named CustomError from Exceptions available. This new Exceptions will raise an error message.

When designing a Python program you should set all user-defined Exceptions to a separate file. And define the file under the name exceptions.py or errors.py .


Example: User-defined Exception in Python

In this example, I will illustrate the user-defined Exception uses in an actual program.

This program will ask users to enter a number until the number they entered exactly matches the number that we have defined. To help users find the number faster we will define a suggestion message for them.

Here is an example when you run the above program:

We will define a call to call the exceptions Error is predefined in the system. The other 2 exceptions are ( ValueTooSmallError and ValueTooLargeError ) that the above program calls are derived from class Error . This is a common way to identify exceptions created by the user define in Python. There are other ways to customize the exceptions .


Customize the Exception class

We have one more way is to customize the Exception class to be able to take other arguments according to our wishes.

To learn how to customize Exception classes, you need to have basic knowledge of OOP programming.

Here I have 1 example:

The output of the above program:

Here we have overridden the constructor of the Exception class to get 2 parameters, salary and message . Then the constructor of the parent Exception class will be called manually with the self.messag argument using super() .

The self.salary property will be used below, then the __str__ method inherits from the Exception class is used to display the corresponding message when the SalaryNotInRangeError is SalaryNotInRangeError .

We can also directly customize the __str__ method by overriding it.

Output of the program:


Conclude

Below I have introduced to you how to customize Exception in Python and some specific examples. If you have any questions, please leave a comment below.


See more details

https://www.programiz.com/python-programming/user-defined-exception

Share the news now

Source : Viblo