Advanced Python Development Course
Chapter
>
Level
Exception Handling
Wrapping up an Exception
Objective
Go to the office and make sure the money supply is properly balanced by using the finally code block and the assert keyword.
Deep in the second floor an office is dedicated to storing funds for future investments for the farm. Itâs about time to check in and make sure all the books are balanced. When dealing with numbers, math errors and other issues are bound to happen so once again exception handling is a good idea to catch and resolve errors.
Aside from try / except and else code blocks there is also the finally code block that allows you to wrap up an exception. In addition to this, the assert keyword is a debug feature that allows you to scan if a code has any errors allowing you to fix bad code.
Start off by walking to the light X mark in front of the office door and using the open() function to open the door to enter. Once inside make your way to the gold X mark and use the collect() function to grab two different constants named: categories and savings . The categories constant is a list that holds money supply of the three categories, named: "exports" , "imports" , "stock" , that need to be verified. The savings constant is a variable that holds money supply that may be needed to ensure the coffers are properly supplied.
Now that all necessary items have been collected itâs time to balance the money supply stored in sacks that will be collected and distributed by a clerk sometime after youâre done. Walk to the dark X mark over the blue carpet, for the X marks over the blue , yellow and red carpets. Here we will use the categories list constant to verify that each sack has all the necessary components before being shipped out.
Each sack is supposed to hold the components found inside the categories list. There are three dictionary constants that correspond to each sack: blue_sack , yellow_sack and red_sack . Run a for loop while standing on the X mark over the blue carpet to verify that the sack has all the required materials then confirm the supply is accounted for.
for x in range(3): player.speak("%s = %s" % (categories[x] , blue_sack[categories[x]])) player.speak("All assets accounted for")
Some of the sacks should have all the required materials, but as per usual in these exercises, you may run into an error. If you encounter an issue you must use the try / except code blocks to catch the error, in this case being a KeyError: which happens if a dictionary key is not found. When this happens we also add finally to the exception, which wraps up the exception by adding a code that always executes at the end of each exception handling. Unlike exceptions, there can only be one finally block per try . For example, in the case of the blue_sack:
try: for x in range(3): player.speak("%s = %s" % (categories[x] , blue_sack[categories[x]])) except: player.speak("Bag is missing %s, adding now" % (categories[x])) player.place(categories[x]) finally: player.speak("All assets accounted for")
Repeat this process on the dark X marks over yellow and red carpets, using the yellow_sack and red_sack dictionary constants. It may not be necessary in some cases as the error occurs only if there is a missing item in the sacks.
Now that the sacks have verified itâs time to move on to the chests in front of the: green , purple and orange carpets. Here we must ensure the money supply is exactly 30 in each chest and then closed afterwards. There are three variable constants corresponding to each chest, named: green_chest, purple_chest, and orange_chest.
The biggest issue with verifying the chests is that we donât know their exact contents, when you are dealing with unknown values you can use the assert keyword. This keyword allows you to verify is a statement youâre declaring is true or false, this is very useful for scanning if your code has any errors. The assert keyword is used conjunction with: try , except , else and final and their various combinations to repair code with errors. For example, in the case of the green_chest :
try: assert(green_chest = 30) except AssertionError: player.speak("Chest is not full %s/30" % green_chest) drop = 30-green_chest savings -= drop player.place(drop) else: player.speak("All assets accounted for") finally: player.close()
In the code above we verify if the green_chest contains the proper amount of money supply using the assert keyword. If it doesnât contain the proper amount, the except block is triggered and we calculate then subtract the missing supply from the savings variable and add it to to the chest. If the supply is complete, the else block is triggered and itâs confirmed all assets are accounted for. Once everything is verified, the finally block is executed and the close() function is initiated to close the chest.
On the X marks over the green , purple and orange carpets, face the chests and run the verification using: green_chest , purple_chest , orange_chest in the respective colored carpets. Once done, walk to the light X mark and use the place() function to store the remainder of the savings variable in the crate in order to complete the level.