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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | >>> class CustomError(Exception): ... pass ... >>> raise CustomError Traceback (most recent call last): ... __main__.CustomError >>> raise CustomError("An error occurred") Traceback (most recent call last): ... __main__.CustomError: An error occurred |
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 | # define Python user-defined exceptions class Error(Exception): """Base class for other exceptions""" pass class ValueTooSmallError(Error): """Raised when the input value is too small""" pass class ValueTooLargeError(Error): """Raised when the input value is too large""" pass # you need to guess this number number = 10 # user guesses a number until he/she gets it right while True: try: i_num = int(input("Enter a number: ")) if i_num < number: raise ValueTooSmallError elif i_num > number: raise ValueTooLargeError break except ValueTooSmallError: print("This value is too small, try again!") print() except ValueTooLargeError: print("This value is too large, try again!") print() print("Congratulations! You guessed it correctly.") |
Here is an example when you run the above program:
1 2 3 4 5 6 7 8 9 10 11 12 | Enter a number: 12 This value is too large, try again! Enter a number: 0 This value is too small, try again! Enter a number: 8 This value is too small, try again! Enter a number: 10 Congratulations! You guessed it correctly. |
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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | class SalaryNotInRangeError(Exception): """Exception raised for errors in the input salary. Attributes: salary -- input salary which caused the error message -- explanation of the error """ def __init__(self, salary, message="Salary is not in (5000, 15000) range"): self.salary = salary self.message = message super().__init__(self.message) salary = int(input("Enter salary amount: ")) if not 5000 < salary < 15000: raise SalaryNotInRangeError(salary) |
The output of the above program:
1 2 3 4 5 6 | Enter salary amount: 2000 Traceback (most recent call last): File " <span class="token tag"><span class="token tag"><span class="token punctuation"><</span> string</span> <span class="token punctuation">></span></span> ", line 17, in <span class="token tag"><span class="token tag"><span class="token punctuation"><</span> module</span> <span class="token punctuation">></span></span> raise SalaryNotInRangeError(salary) __main__.SalaryNotInRangeError: Salary is not in (5000, 15000) range |
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | class SalaryNotInRangeError(Exception): """Exception raised for errors in the input salary. Attributes: salary -- input salary which caused the error message -- explanation of the error """ def __init__(self, salary, message="Salary is not in (5000, 15000) range"): self.salary = salary self.message = message super().__init__(self.message) def __str__(self): return f'{self.salary} -> {self.message}' salary = int(input("Enter salary amount: ")) if not 5000 < salary < 15000: raise SalaryNotInRangeError(salary) |
Output of the program:
1 2 3 4 5 6 | Enter salary amount: 2000 Traceback (most recent call last): File "/home/bsoyuj/Desktop/Untitled-1.py", line 20, in <span class="token tag"><span class="token tag"><span class="token punctuation"><</span> module</span> <span class="token punctuation">></span></span> raise SalaryNotInRangeError(salary) __main__.SalaryNotInRangeError: 2000 -> Salary is not in (5000, 15000) range |
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