[Tutor] User defined exceptions

Alan Gauld alan.gauld at yahoo.co.uk
Fri Oct 15 07:14:52 EDT 2021


On 15/10/2021 08:03, Manprit Singh wrote:

> I have written an example on user defined exceptions, just to check if my
> understanding is correct, 

The understanding is correct in terms of how to write the code
and how the mechanism works.

However, in general, it is best to use a built in exception
wherever possible, then pass a unique message when it is raised.
In this case a ValueError would seem to be entirely appropriate.

Even if you did have a reason to define your own, it might be better to
derive it from ValueError rather than Exception, since then it could be
caught by an "except ValueError" clause as well as a specific "except
MarksError"

Part of the reason for adopting a general approach is that you may
have a function that gets used by another user in a different context.
Possibly even as part of a collection of functions. In that case the
user will possibly put try/except around the function call
but it becomes tedious to have an except for every possible
exception type from every possible function. So, writing

for f in functions:
   try:
      result = f()
      # do something with result
   except ValueError:  #...
   except TypeError:   #...
   except:  # catch all maybe???

Would catch the most common cases with a generic handler for the rest.
By deriving your error from ValueError it will be caught by the
first except rather than falling through to the default handler.
Or better still just use a ValueError directly.

The other pint about using a custom error is that it adds to the
documentation. If you raise a standard exception there is no real
need to describe it in the documentation but if you define your own
error then the user as to know all about it, what it signifies,
and so on. More work for you as author and more effort for the user.

> 
> 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}')

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos




More information about the Tutor mailing list