[Tutor] Using try, except else inside function definition

Alan Gauld alan.gauld at yahoo.co.uk
Wed Oct 20 16:29:17 EDT 2021


On 20/10/2021 19:29, Manprit Singh wrote:

> def count_words(filename):
>     try:
>         with open(filename) as fileobj:
>             content = fileobj.read()
> 
>     except FileNotFoundError:
>         print(f'Sorry the file {filename} not exists')
> 
>     else:
>         words = content.split()
>         cntwd = len(words)
>         print(f'The file {filename} has {cntwd} words')
> 
> This is working fine, my question is can we place try, except & else blocks
> inside the function definition as done above.

The fact it is "working fine" tells you that you can.
And indeed that is perfectly normal.

The only thing I'd say is that the function is called
count words so I'd expect it to return a value not
print a message. The printing should be done outside
the function and the function just return the value
or raise the exception.

> def indexofelement(seq, ele):
>     try:
>         if ele not in seq:
>             raise ValueError
>     except ValueError:
>         return -1

This is kind of pointless. Instead of raising the
ValueError and immediately catching it just
return -1. Handling errors is relatively expensive
so if you don't need to do it its better to just
return the value directly. However in this case
you are probably better removing the try/except
construct and just raise the ValueError with a
suitable message.

>     else:
>         for ind, val in enumerate(seq):
>             if val == ele:
>                 return ind

> Returning values in this way from the function is ok ?

Its OK but its an old fashioned way of handling
errors - especially since -1 is a valid index in Python.
If a user used the index without checking they would
get a result(albeit a faulty one. If you raise the
exception instead the user has no choice but be
aware of it either by handling it or via the stacktrace
if they ignore it.

Part of the rationale for try/except style error handling
is to remove the need for checking for magic return values.

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