exceptions and items in a list

Peter Hansen peter at engcorp.com
Mon Jan 10 19:32:48 EST 2005

rbt wrote:
> Andrey Tatarinov wrote:
>> # skip bad object and continue with others
>> for object in objects:
>>     try:
>>         #do something to object
>>     except Exception:
>>         pass
> Thanks Andrey. That's a great example of how to do it.

Actually, it's not really a "great" example, since it catches
_all_ exceptions that might happen, and quietly ignores
them.  For example, in the following code, you might not
realize that you've made a typo and none of the items in
the list are actually being checked, even though there is
obviously no problem with any of these simple items
(integers from 0 to 9).

def fornat_value(val):
     return '-- %5d --' % val

L = range(10)
for val in L:
         print format_value(val)
     except Exception:

It's almost always better to identify the *specific*
exceptions which you are expecting and to catch those,
or not do a simple "pass".  See Vincent's response,
for example, where he explicitly asks only for ValueErrors
and lets others propagate upwards, to be reported.

(I realize these were contrived examples, but examples
that don't mention this important issue risk the propagation
of buggy code...)


More information about the Python-list mailing list