Catching a Built-in Exception
And this is a long list. I took it from the documentation, and I had to cut it up because there’s so many built-in errors. You can see also how they all inherit from the
BaseException, and then there’s this
Exception class that you used towards the beginning of this course.
You can pause this video for a second and see if you can find the
FileNotFoundError. I’ll give you a second for that. And now let’s head back over to the code and handle the
FileNotFoundError, make sure that the program doesn’t quit if the logging file doesn’t exist.
So back over here, let’s add another message. Copy this just to say that we’re reading the logging file. And then you’re attempting to open a file that doesn’t exist, so you want to wrap this again into a
except block. I’m going to say “Try to open this file,” and then, “Print out the log file,” and “
except if you have a
Okay, so this is the common
except block that you can use often and that you will often see used in Python code, where you expect a certain exception to occur and then you do something if it occurs indeed.
So now I run this code. You will see that the important macOS work gets done. There’s no problem, the work happened, everything was great. No exception occurred, which is why the code inside of the
else block started running.
It tells you that it’s going to start reading the logging file. But now, in here, you have another
except block where it attempts to open this file, and it doesn’t find the file because it doesn’t exist.
But instead of ending the script, you’re catching this
FileNotFoundError that comes up and printing out a message plus also the error message that happened before. And your script continues, which means that also this
"happens after" still prints after that.
And this is how you can catch any sort of exception in Python, be it one that you defined yourself, like you did here with the
WrongOsError, or just one of those built-in ones like the
FileNotFoundError. And again, there’s a lot of built-in exceptions, and it generally makes sense to just use one of those built-in exceptions instead of making and subclassing your own. Just make sure that you know which ones can get raised and in which condition you want to catch what exception. This is how you can catch built-in exceptions in Python.
Become a Member to join the conversation.