Handling the Success Case With else
00:00
In the previous lesson, you learned how to use a try
… except
block to handle your exceptions, and in this lesson, you will learn about an additional keyword you can add to this try
… except
block, which is the else
keyboard.
00:13
This executes when no exception was raised in the try
… except
block.
00:20
Keep in mind that you can have multiple except
statements inside of a try
… except
block. Currently, you only have one, and it’s already got a nice error printed out. And now if you run the macos_interaction()
, there’s no exception that happens and you only see these two statements.
00:40
But if you run the linux_interaction()
on a Mac system, you will see that the WrongOsError
gets raised, but then also handled—gets caught—by this except
statement and then this code in here happens. But so what happens if you add this else
statement here? You want to print out, say,
01:08
"No problem, work done."
The code in this else
block is only going to execute if no error was raised, so if I run it with Linux, you’re going to see it’s not going to run at all, but if I switch back to macOS, then no exception, the WrongOsError
, or no other exception is going to get raised, and then the code inside of the else
block here is going to execute as well.
01:38 Now, what do you want to do in here? For example, you could go ahead and open up the logging file and read it, because all of the important macOS work got successfully done, so let’s look at what happened there. So I’m going to open up a logging file
02:00 and then read it and print it to the console.
02:09 Okay. That’s going to be interesting, right? We want to know what was the work that happened, so if I go ahead and run this,
02:18
I get a FileNotFoundError
. And of course, you get that because you don’t have this file.log
. There was no logging that you implemented, so Python can’t find this file that you’re trying to open, and this is an example of a built-in exception that Python raises for you.
02:34
This one is called FileNotFoundError
. You see it’s quite similar to the custom one that you built or some of the other exceptions you saw earlier, and this one specifically tells you that you attempted to do something with a file that Python couldn’t find. Now, in the next lesson, you’ll learn how you can handle a built-in exception and you’re also going to take a look at which ones exist.
02:57
But to sum up this part with the else
statement, essentially, you can add it to a try
… except
block and you can write some code in there that’s only going to run if no exception was raised anywhere in the try
… except
block. All right, and in the next lesson, you’ll handle this pesky FileNotFoundError
with another try
… except
block inside of your try
… except
block.
Become a Member to join the conversation.