Let exception fire or return None

Thomas 'PointedEars' Lahn PointedEars at web.de
Thu Apr 30 08:05:22 EDT 2015


Cecil Westerhof wrote:

> I have a function to fetch a message from a file:
>     def get_indexed_message(message_filename, index):
>         """
>         Get index message from a file, where 0 gets the first message
>         """
> 
>         return open(expanduser(message_filename),
>         'r').readlines()[index].rstrip()
> 
> What is more the Python way: let the exception fire like this code
> when index is to big, or catching it and returning None?

It is not only the Python way, it is the *correct* way to throw/_raise_ an 
exception if the language allows it.  Think of what “exception” means: there 
is an *exceptional* (not normal) circumstance that causes execution of the 
function/method to stop.

Return values and status values to indicate such errors were used before 
exceptions, and are still used in languages that do not have exceptions.  
But return values only work if you can tell them apart from success values.  
You have only one error condition now.  If you have a different error 
condition in the future, you need a different return value for that to tell 
it apart from the first error condition.  

There comes a point where you are out of new return values for new error 
conditions such that you cannot tell them apart from success values anymore.  
And functions setting status values to refine return values are not 
reentrant.  But you can always throw a different type of exception or the 
same type of exception with a different message.

> I suppose working zero based is OK.

Yes, it is the common approach.

-- 
PointedEars

Twitter: @PointedEars2
Please do not cc me. / Bitte keine Kopien per E-Mail.



More information about the Python-list mailing list