else, we’ve seen how to run certain code when an exception occurs and other code when it does not. There is also a way to execute code regardless of whether an exception occurs - the
Here is our final flow chart demonstrating
Let’s return to our fictional login program from earlier and examine a use case for the
try: check_password() except ValueError: print('Wrong Password! Try again!') else: login_user() # 20 other lines of imaginary code finally: load_footer()
In the above program, most of our code stayed the same. The one change we made was we added the
finally clause to execute no matter if the user fails to login or not. In either case, we use an imaginary function called
load_footer() to load the page’s footer. Since the footer area of our imaginary application stays the same for both states, we always want to load it, and thus call it inside of the
Note that the
finally clause can be used independently (without an
else clause). This is a convenient way to guarantee that a behavior will occur, regardless of whether an exception occurs:
try: check_password() finally: load_footer() # Other code we always want to run
Let’s put the
finally clause into practice for our Instrument World application!
Instrument World maintains a database (in this case a large dictionary) with instrument information that any store can access.
The current program displays information from the database for a particular instrument. Take some time to look over
instrument.py to get better acquainted with the program.
Run the code to examine the output!
Since the database server Instrument World uses can only have a limited number of users connected to it, we want to make sure that we disconnect from it after attempting to retrieve information, even if an exception occurs.
finally clause that calls
database.disconnect_from_database(). Observe the output of the exception handling when we hit an exception by running the code!
instrument to have a value of
'Kora'. Run the code to observe the
finally clause executing even when we don’t hit an exception.