Else
suggest changeCode 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()
# prints: one
# then the else clause raises ValueError, which is not caught
This else is not an elif. A following condition has to be a nested if under that else:
try:
...
except ...:
...
else:
if ...:
...
elif ...:
...
else:
...
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents