Function to determine list max without itertools

Grant Edwards grant.b.edwards at gmail.com
Mon Apr 22 10:44:05 EDT 2019


On 2019-04-20, Michael Torrie <torriem at gmail.com> wrote:
> On 04/19/2019 04:01 AM, Sayth Renshaw wrote:
>> def max_try(listarg):
>>     myMax = listarg[0]
>>     try:
>>         for item in listarg:
>>             if item > myMax:
>>                 myMax = item
>>     except TypeError:
>>         print(f'Only numbers are supported, this entry "{item}" was not')
>>         pass
>> 
>>     return myMax
>
> If I were you I wouldn't catch that exception.  The reason is that a
> non-number is something your code just can't handle correctly anyway, so
> better to let that original exception bubble up to the caller who can
> deal with it.  By catching this exception, your code will fail, but
> still return as if it succeeded.
>
> Others may disagree. But I rarely catch exceptions in my code unless my
> code specifically wants or needs to deal with them.

I agree: In general, in a function, you only catch an exception if you
can _fix_ the problem.  [Though there may be some some cases where you
want to log the exception in some specific manner and re-raise it.]
If the function can't fix the problem, then leave it to the caller to
decide what to do about it.

At the very top level _sometimes_ you want to have one single, global,
try/except to catch all exceptions and handle the nofication and exit
in a non-default way.  For example: in a GUI application, it's
possible that nobody will see an excption message and stack trace
that's sent to stderr.  A good GUI framework would already handle
that, but not all do.

-- 
Grant Edwards               grant.b.edwards        Yow! How many retured
                                  at               bricklayers from FLORIDA
                              gmail.com            are out purchasing PENCIL
                                                   SHARPENERS right NOW??




More information about the Python-list mailing list