Else

suggest change

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()
# 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:
        ...

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents