exceptions and items in a list

Steve Holden steve at holdenweb.com
Tue Jan 11 02:15:53 CET 2005


vincent wehren wrote:

> rbt wrote:
> 
>> If I have a Python list that I'm iterating over and one of the objects 
>> in the list raises an exception and I have code like this:
>>
>> try:
>>     do something to object in list
>> except Exception:
>>     pass
>>
>> Does the code just skip the bad object and continue with the other 
>> objects in the list, or does it stop?
>>
>> Thanks
> 
> 
> Fire up a shell and try:
> 
>  >>> seq = ["1", "2", "a", "4", "5", 6.0]
>  >>> for elem in seq:
> ....     try:
> ....        print int(elem)
> ....     except ValueError:
> ....        pass
> 
> 
> and see what happens...
> 
> -- 
> Vincent Wehren

I suspect the more recent versions of Python allow a much more elegant 
solution. I can't remember precisely when we were allowed to use 
continue in an except suite, but I know we couldn't in Python 2.1.

Nowadays you can write:

Python 2.4 (#1, Dec  4 2004, 20:10:33)
[GCC 3.3.3 (cygwin special)] on cygwin
Type "help", "copyright", "credits" or "license" for more information.
  >>> for i in [1, 2, 3]:
  ...   try:
  ...     print i
  ...     if i == 2: raise AttributeError, "Bugger!"
  ...   except AttributeError:
  ...     print "Caught exception"
  ...     continue
  ...
1
2
Caught exception
3
  >>>

To terminate the loop on the exception you would use "break" instead of 
"continue".

regards
  Steve
-- 
Steve Holden               http://www.holdenweb.com/
Python Web Programming  http://pydish.holdenweb.com/
Holden Web LLC      +1 703 861 4237  +1 800 494 3119



More information about the Python-list mailing list