[Tutor] User defined exceptions
Manprit Singh
manpritsinghece at gmail.com
Fri Oct 15 03:03:40 EDT 2021
Dear Sir,
I have written an example on user defined exceptions, just to check if my
understanding is correct, I request you to read the points and let me know
if those are correct or not
class MarksError(Exception): # A simple user defined exception
pass
def grades(glist, score):
if score < 0 or score > 100:
raise MarksError("Invalid Score") # Argument to raise is an
exception instance
for ch, rg in glist:
if score < rg:
return ch
lst = [("F", 60),
("D", 70),
("C", 80),
("B", 90),
("A", 101)]
try:
marks= int(input("Enter marks"))
grade = grades(lst, marks)
except MarksError as err:
print(err)
else:
print(f'for {marks} marks the grade is {grade}')
This program is for printing the grade of a student based on marks .
1) In the starting, I have written a very simple user-defined Exception
class- MarksError, simply placing a pass inside this class causes no extra
addition, this class inherits everything from the Exception class.
2) Inside the function def grades, i have used raise keyword to raise an
exception . Just besides the raise keyword I have written
MarksError("Invalid Score"), which is basically an instance of the
exception class MarksError with the argument "Invalid Score".
3) In the except block given below:
except MarksError as err:
print(err)
variable err is bound to the exception instance written with raise keyword,
hence print(err) will print the argument "Invalid Score", when exception
is handled.
Kindly comment
Regards
Manprit Singh
More information about the Tutor
mailing list