[Tutor] User defined exceptions

Alan Gauld alan.gauld at yahoo.co.uk
Tue Oct 19 12:42:57 EDT 2021


On 19/10/2021 11:49, Manprit Singh wrote:
> 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}'

> 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.

That's correct and if you sere doing a lot of work with that exception
might be worth doing. But in practice, just passing the message into
the exception tends to be more flexible and less work.

Remember that we generally don't catch an exception unless we can
do something to correct the problem or to convert the stacktrace
into a more user friendly form (eg. inside a GUI/web app). So when
creating the exception class think about how you will be using it
when handling the exception. In this case the only use-case I can
see is during interactive input when you'd repeat the request to
the user. In that case raising the exception with the relevant
error string and in the handler simply printing err.args[0]

-- 
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