User Defined Exception in Python
In this class, we discuss User Defined Exception in Python.
For Complete YouTube Video: Click Here
User-Defined Exception
The reader should have prior knowledge of Exceptions. Click here.
Take an example and understand the concept of the user-defined Exception.
In our last class, we discussed that in all the exception classes, the base class is Exception.
To create a user-defined Exception, we have to inherit the class Exception.
class MarksNotinRange(Exception):
def __init__(self, Marks, message="Marks not in (0, 100) range"):
self.marks = Marks
self.message = message
super().__init__(self.message)
marks = int(input("Enter marks: "))
if not 0 < salary < 100:
raise MarksNotinRange(marks)
Enter marks: 101
Output:
MarksNotinRange: Marks not in (0, 100) range
In the above program, we defined the class MarksNotinRange.
The class MarksNotinRange is inheriting the class Exception.
We defined a constructor, and it is taking marks.
The default message is taken in the constructor, and the message is given to the superclass constructor.
The constructor in the class Exception is assigned with the message given in class marks, not in range.
Similarly, the inbuilt python exceptions are also using separate classes for different exceptions, and the messages are given in each class.
We had seen the messages given by inbuilt exceptions in our previous class.
We use the keyword raise to call an exception. It is shown in the program above.
Example to Catch User-Defined Exception
class MarksNotinRange(Exception):
def __init__(self, Marks, message="Marks not in (0, 100) range"):
self.marks = Marks
self.message = message
super().__init__(self.message)
marks = int(input("Enter marks: "))
try:
if not 0 < salary < 100:
raise MarksNotinRange(marks)
except MarksNotinRange:
print("marks not matching")
Enter marks: 101
Output:
marks not matching
In the above example, we defined an except block to catch the Exception.
Analyze the code above for better practice. The basics are discussed in the previous class.