But I execute the operation in the else:
try:
except ZeroDivisionError:
print "whoops! divide by zero..."
else:
execute( )
The exeption is produced after.
Well... the above is not even valid Python syntax.
The "except...:" has to align with the "try:", and the
statements that may generate the exception come between the "try:" and
the "except...:".
try:
execute()
except ...:
print "error"
An "else:" clause on a "try:" is executed only if no exceptions
occur IN the block. From the language reference (you have read this,
haven't you?"
PLR> The optional else clause is executed if and when control flows off
the end of the try clause.7.1 Exceptions in the else clause are not
handled by the preceding except clauses.
(the 7.1 is a footnote marker)
In a very contrived example, and without specifying particular
exceptions:
try:
fi = open("some.file")
try:
while 1:
dta = fi.readline()
if not dta: break
#do stuff
except ...:
print "Error Reading"
except ...:
print "Error opening"
else:
fi.close()
This example presumes that a failure opening the file means there is
nothing to close. Otherwise it processes the file contents. An error
reading the file will not raise an exception in the outer try, so the
outer try exits via the else clause -- which closes the open file; if
the file wasn't opened the outer except triggered, and the else is not
used.
--