Cleaning Up With finally
In this lesson, you will learn about yet another keyword that you can add to the
except block, which is called
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.
And since this whole project here that you were building mostly consists of logging, let’s add another logging in here. I’m going to say
as part of the outermost
I’m going to say
print("Cleaning up despite any exceptions."). So this is going to run no matter what, and then this
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.
else block executes, no problems. Then the logging file is attempted to be read. It doesn’t exist, you catch the exception and print out something.
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.
01:39 Now let’s take a look at what happens with the Linux interaction. You know that this is going to cause an error on my system. So if I run this instead, the output is much shorter.
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.