Code in an else block will only be run if no exceptions were raised by the code in the try
block. This is useful if you have some code you don’t want to run if an exception is thrown, but you don’t want exceptions thrown by that code to be caught.
For example:
try:
data = {1: 'one', 2: 'two'}
print(data[1])
except KeyError as e:
print('key not found')
else:
raise ValueError()
# Output: one
# Output: ValueError
Note that this kind of else:
cannot be combined with an if
starting the else-clause to an elif
. If you have a following if
it needs to stay indented below that else:
:
try:
...
except ...:
...
else:
if ...:
...
elif ...:
...
else:
...