[Tutor] casting string to integer in a list of lists
wesley chun
wescpy at gmail.com
Fri Jan 9 00:45:56 CET 2009
>> except:
>> pass
>>
>> try not to code these 2 lines in anything that you do because it will
>> come back to haunt you when something is not working right but you
>> can't find any errors. that's because this code masks and throws away
>> everything!!
>
> there are two potential error types: IndexError and ValueError. I assumed that if
> either one occurred, we would want to leave that particular list member (if
> it exists) as-is (hence the pass).
> :
> - catch the exception, test to see whether it's an IndexError or a
> ValueError, and if not then do something;
> :
as opposed to the above...
except (IndexError, ValueError):
pass
...is much more acceptable. there are 2 general conventions:
- catch errors explicitly (as to not mask the others) and pass/ignore
- catch 'em all (except Exception) and do *some*thing (not pass)
both of those cases shows that you did your due diligence and that
you're just not blindly throwing things away.
> Generally, if there are two or more "acceptable" errors that you can foresee,
> but you still want to catch any others, what's an elegant, readable, and
> computationally-cheap way to do it? Maybe a dictionary of exceptions...?
A tuple of exceptions works, just like what we did above, and more,
i.e., (IndexError, ValueError, TypeError, KeyError...
hope this helps!
-- wesley
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
"Core Python Programming", Prentice Hall, (c)2007,2001
"Python Fundamentals", Prentice Hall, (c)2009
http://corepython.com
wesley.j.chun :: wescpy-at-gmail.com
python training and technical consulting
cyberweb.consulting : silicon valley, ca
http://cyberwebconsulting.com
More information about the Tutor
mailing list