Recovering From Errors
00:00 Now you’re going to look at another aspect of control flow, which is errors and recovering from them. But before you can recover from errors, you’re going to need to learn what errors and exceptions are. And to do this, you’re going to look at different types of errors and exceptions.
First, take a look at a
SyntaxError. Most of the other errors you’ll encounter are actually exceptions, which means that they can be recovered from. However, a
SyntaxError is a proper error in the sense that it can’t be recovered from. If you have a
SyntaxError, your program just won’t run, no matter what you do.
An example of a
SyntaxError is using
if without a condition or a colon. As you can see, if you try and execute just a bare
if, you’ll get a
SyntaxError, and it will tell you that the syntax is invalid.
And the constructor, you can tell it’s a constructor by the brackets (
()) here, as if it’s a function. But instead of passing in something that resembles a number, you’re passing in
int() can’t understand this. It says, well,
"hello" is not even close to a number, so it raises a
ValueError saying that it’s an
invalid literal for int() with base
10. It’s not a number, basically. So this is a
ValueError, which raises an exception that can be caught. More on what “can be caught” means in the following lesson.
TypeError you might have run into already. If you try and add a string to a number, as is the case in this example—it’s adding the string
"1", so it’s one enclosed in quotation marks, plus
2, a number that’s not enclosed in quotation marks—and they’re saying there’s a
TypeError here because their types are wrong here, and it’s saying, you can only concatenate a string to a string, not an integer to a string. A
So say you try to print a variable,
does_not_exist. You haven’t declared this variable,
does_not_exist, and so you’ll get a
NameError with a message saying that the variable
'does_not_exist' is not defined.
Now that’s a mind-bogglingly large number, which Python will protect you from and will give you an
OverflowError. Now again, all of these errors, apart from the
SyntaxError, are ones that you can handle, and that will be covered in the next lesson.
03:12 In this lesson, you’ve covered errors and exceptions, the differences between them, and you’ve looked at different types of errors and exceptions. You’ve seen how errors and exceptions have quite descriptive names and helpful messages to help you debug them.
03:27 There are many more errors and exceptions that you haven’t covered here. And in fact, you can even define your own errors and exceptions with custom names and messages. That’s just for some context, though. Don’t worry about it yet, as you don’t need custom errors and exceptions while learning the basics.
Become a Member to join the conversation.