[Tutor] for loops and exceptions
Kent Johnson
kent37 at tds.net
Thu Mar 30 15:21:56 CEST 2006
Matthew White wrote:
> Hello,
>
>>From a general style and/or programmatic perspective, which is a "better"
> way to write this bit of code?
Hmm, neither?
>
> try:
> (dn, attrs) = conn.search_s(search_base, search_scope, search_filter, search_attrs):
> except Exception, e:
> warn_the_user(e)
> do_something_useful()
>
> for (name, data) in (dn, attrs):
> print '%s' % (name)
> for key, value in data.iteritems():
> print '%s => %s' % (key, value)
This will run the for loop even if you get an exception. I think the for
loop is buggy, too, it is different from the one below.
>
> OR
>
> try:
> for dn, attrs in conn.search_s(search_base, search_scope, search_filter, search_attrs):
> print dn
> for key, value in attrs.iteritems():
> print '\t%s => %s' % (key, value)
> print
> except Exception, e:
> warn_the_user(e)
> do_something_useful
This might be OK. It will catch exceptions in the for loop, which you
may or may not want.
If this code is at a low level of your program, it's best to only catch
expected exceptions, and let unexpected exceptions propagate to a higher
level. At the higher level, you can have a generic except block that
reports the error and moves on. This is often in a top-level loop or
event handler. Your code has elements of both - code that does real work
with a generic except block that reports errors.
Anyway here is a construction that is very useful for catching just the
exceptions you expect to see from a bit of code, while running the rest
of the code outside of the try block.
try:
(dn, attrs) = conn.search_s(search_base, search_scope,
search_filter, search_attrs):
except ConnectionError, e:
warn_the_user(e)
do_something_useful()
else:
print dn
for key, value in attrs.iteritems():
print '\t%s => %s' % (key, value)
print
The idea is to put as little code as possible in the scope of the try,
and to catch as few exceptions as possible. If no exception is raised,
the else: block will run. If there is an exception in that code, it will
propagate to a higher level.
Kent
More information about the Tutor
mailing list