The try…except…finally statements

You can use the finally clause instead of the else clause with a try statement. The difference is that the statements inside the finally block will always be executed, regardless whether an exception occurs in the try block. Finally clauses are also called clean-up or termination clauses, because they are usually used when your program crashes and you want to perform tasks such as closing the files or logging off the user. Here is the syntax:

try:
    statements # statements that can raise exceptions
except:
    statements # statements that will be executed to handle exceptions
finally:
    statements # statements that will always be executed

Here is an example:

try:
    age=int(input('Enter your age: '))
except:
    print('You have entered an invalid value.')
finally:
    print('There may or may not have been an exception.')

The output:

>>> 
Enter your age: 55
There may or may not have been an exception.
>>> RESTART
>>> 
Enter your age: a
You have entered an invalid value.
There may or may not have been an exception.
>>>

Note that the print statement inside the finally code block was executed regardless of whether the exception occurred or not.

Geek University 2022