try/except in a loop

Chris Kaynor ckaynor at zindagigames.com
Wed May 2 16:27:26 EDT 2012


On Wed, May 2, 2012 at 1:12 PM, Prasad, Ramit <ramit.prasad at jpmorgan.com> wrote:
>> > I have multiple objects, where any of them can serve my purpose..
>> However
>> > some objects might not have some dependencies. I can not tell before
>> hand if
>> > the all the dependencies exsit. What i want to is begin processing from
>> the
>> > 1st object, if no exception is raised, i am done.. if an exception is
>> > raised, the next object is tried, etc  Something like
>> >
>> > objs = [... ]
>> > try:
>> >   obj = objs[0]
>> >   obj.make()
>> > except Exception, e:
>> >   try:
>> >       obj = objs[1]
>> >       obj.make()
>> >   except Exception, e:
>> >      try:
>> >         obj = objs[2]
>> >         obj.make()
>> >      except Exception, e:
>> >        continue
>> >
>> > The problem is the length of the list of objs is variable... How can i
>> do
>> > this?
>>
>>
>> for obj in objs:
>>     try:
>>         obj.make()
>>     except Exception:
>>         continue
>>     else:
>>         break
>> else:
>>     raise RuntimeError('No object worked')
>
>
> I think you misunderstand the else clauses.
>
>>>> for obj in [ 1,2,3,4 ]:
> ...     try:
> ...         print obj
> ...     except Exception:
> ...         print 'EXCEPTION'
> ...     else:
> ...         print 'NO EXCEPTION'
> ... else:
> ...     print 'NO OBJECTS'
> ...
> 1
> NO EXCEPTION
> 2
> NO EXCEPTION
> 3
> NO EXCEPTION
> 4
> NO EXCEPTION
> NO OBJECTS

You left out the break in the try clause's else that I had. That break
statement causes the for loop to exit early if there is no exception,
and thus the for loop's else clause does not run:

>>> for obj in [ 1,2,3,4 ]:
...     try:
...             print obj
...     except Exception:
...             print 'EXCEPTION'
...     else:
...             print 'NO EXCEPTION'
...             break
... else:
...     print 'NO OBJECTS'
...
1
NO EXCEPTION

>
>
> Ramit
>
>
> Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology
> 712 Main Street | Houston, TX 77002
> work phone: 713 - 216 - 5423
>
> --
>
> This email is confidential and subject to important disclaimers and
> conditions including on offers for the purchase or sale of
> securities, accuracy and completeness of information, viruses,
> confidentiality, legal privilege, and legal entity disclaimers,
> available at http://www.jpmorgan.com/pages/disclosures/email.
> --
> http://mail.python.org/mailman/listinfo/python-list



More information about the Python-list mailing list