Search notes:

Python statements: else clause

Some statements have an else clause:

The else clause executed if successfully completed

In the for, try and while statements, the else clause can be interpreted as to mean successfully completed.
In the loop statements, the else clause is executed if the loop statement is not prematurely exited with a break statement.
In a try statement, the else clause is executed if no exception was caught:
def raise_if(condition):

    if condition:
       print('throwing execption because condition is true')
       raise Exception()

    else:
       print('condition is false, nothing thrown')


try:
     raise_if(True)
except:
     print('executed if exception was caught')
else:
     print('executed if no exception was caught')
finally:
     print('always executed')

print('-----------------')

try:
     raise_if(False)
except:
     print('executed if exception was caught')
else:
     print('executed if no exception was caught')
finally:
     print('always executed')
Github repository about-Python, path: /statements/else-clause/try.py

Index