[Tutor] User defined exceptions
Manprit Singh
manpritsinghece at gmail.com
Tue Oct 19 06:49:35 EDT 2021
Dear Sir,
With some more modifications, I have written a user defined class and
illustrated its use. Although I know in this example raising ValueError is
good. The example here is to understand what further we can do with user
defined exceptions: Just want you to read my comments at bottom and check
if these are correct or not.
class MarksError(Exception): # A simple user defined exception
def __init__(self, high, low):
self.high = high
self.low = low
def __str__(self):
return f'Value must between {self.low} to {self.high}'
def grades(glist, score):
if score < 0 or score > 100:
raise MarksError(100, 0)
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}'
When i run this code with appropriate marks it displays correct grade
Enter marks78
for 78 marks the grade is C
When i run this code with marks > 100 or marks < 0
Enter marks107
Value must between 0 to 100
The Exception MarksError is raised, and due to the variable err in the
except block is bound to the exception instance raised inside the function
grades, print(err) will print the string returned by def__str__ inside the
class MarksError, so the message "Value must between 0 to 100" is printed.
Regards
Manprit Singh
More information about the Tutor
mailing list