[Tutor] A problem involving exception handling, need suggestions to improve further

Alan Gauld alan.gauld at yahoo.co.uk
Wed Nov 4 18:21:41 EST 2020


On 04/11/2020 14:42, Manprit Singh wrote:

> In the below written mail , we are only raising an exception . I need to
> make a program that can end normally while displaying a message 

Thats fine and there is no problem doing that as pointed out by Mats and
Cameron. The difference is in a function. You do not want a function
that performs calculations printing things. Why? Because it would make
the function unusable in a GUI program, a web application, or a server
process running in the background and writing top a log file.

One of the main reasons we put things into functions is so that they
can be reused 9multiple times within a single program or, even better,
multiple times across multiple programs. To do that we want functions
to return values or raise exceptions which can be used by the UI
parts of the program. That way if an exception occurs the GUI
program can pop up a dialog box, the web app can display an
error page(or an error dialog) and the server process can
write it to the log file. And of course a CLI program can just
print the message. A print inside the function would be much
harder to handle in each case except the last.

Incidentally, you can pass a string into the exception when you
raise it and access that string in the except handler where you
catch it:

def f(x):
   if x < 0: raise ValueError("%d is less than zero" % x)
   return int(x**0.5)

try:
   print(" The int root of -5 is: %d" % f(-5))
except ValueError as err:
   print(err)   # prints "-5 is less than zero"

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