Cleaning Up With finally
00:07 It’s going to be the last keyword that you learn about here. This keyword opens up a code block that is going to always run. It doesn’t matter whether or not an exception got raised, it’s just always going to execute this code afterwards.
And this is going to be important, for example, if you want to close a file stream or just for logging, for example. There’s a couple of scenarios where you would want to definitely run a piece of code as part this
except block at the end of it, no matter whether an exception got raised and caught or not.
01:02 Let’s try it out with these two scenarios of a failing and of a working run of this code. First, let’s have the working one from before. If I run this, you see the important macOS work gets done.
Finally, inside of the
finally block, this executes and it cleans up despite any exceptions. So you could be, for example, closing a file stream that you opened up earlier somewhere in your code.
What happens is that the first OS error gets raised and caught here. This gets printed out, else the whole
else block gets skipped, so nothing in here happens, but the
finally block still executes and this final print statement also gets printed to the console, as well as your program doesn’t quit because you’re handling all of the exceptions that got raised, and so it continues running and you get this final message printed out as well.
And that’s what’s there to say about the
finally keyword. You can add it to your
except block, which makes it consist of this
finally, and you saw all of these keywords implemented in the example.
02:35 And that’s it about the course! In the next and final lesson, you’re going to go again over a quick summary of what you learned about in this course and wrap it up. Then I’ll let you go ahead and write your exceptions into your own code.
Become a Member to join the conversation.