Why have the code that must be executed if the try clause does not raise an exception within the try construct? Why not simply have it follow the try/except at the same indentation level?
The else
block is only executed if the code in the try
doesn’t raise an exception; if you put the code outside of the else
block, it’d happen regardless of exceptions. Also, it happens before the finally
, which is generally important.
This is generally useful when you have a brief setup or verification section that may error, followed by a block where you use the resources you set up in which you don’t want to hide errors. You can’t put the code in the try
because errors may go to except
clauses when you want them to propagate. You can’t put it outside of the construct, because the resources definitely aren’t available there, either because setup failed or because the finally
tore everything down. Thus, you have an else
block.
Consider:
lis = range(100)
ind = 50
try:
lis[ind]
except:
pass
else:
#Run this statement only if the exception was not raised
print "The index was okay:",ind
ind = 101
try:
lis[ind]
except:
pass
print "The index was okay:",ind # this gets executes regardless of the exception