Differentiating Exceptions From Syntax Errors
In this lesson, you will learn how to differentiate between exceptions and syntax errors in Python. To show an example, I will head over to VS Code, and I have a script open that I called
00:13 I’m just going to write a bit of code in here, and you will keep using this script throughout the course and then build a small program in there. So you can go ahead and create that file as well, or just watch me for now, because I’m just going to demonstrate these two errors as a start.
A syntax error is when something goes wrong during parsing, so when Python is reading your code and doesn’t know what to do with it. An example for that would be that I’m trying to call
print(), and I’m going to say
3 divided by
1, but then accidentally, I make an additional parentheses here.
00:50 So this is the crucial, additional, leftover parentheses that’s always a story with programmers, where you just accidentally left something in there that’s very small but completely breaks your program.
It’s just not valid Python code, and this is why it runs into a syntax error. So if I try to run this code by typing
python main.py, you see that there’s the
SyntaxError coming up, and Python just quits the run of this script because it doesn’t know how to interpret this and tells you why.
01:39 In this case, there’s an unmatched parenthesis. You might not see such detailed error information because they were added in more recent versions of Python, but you will definitely see a syntax error and Python complaining that it doesn’t know what to do with the code that you wrote.
02:11 So, I can write this code. That is completely valid Python code. There’s the right amount of brackets, there’s integers, there’s an operator, there’s a function call. And this is all valid Python syntax, so Python can read this fine and you can attempt to execute it. However, it’s going to run into an error because you can’t divide by zero.
then Python throws a
ZeroDivisionError. And this is an exception, a built-in exception in Python that happens every time your program would attempt to divide a number by zero, which is just mathematically not allowed.
03:02 So, to recap, you have parsing errors, which is, “Something’s wrong with the syntax that you wrote,” and Python throws a syntax error for those. And then you have errors during execution, and these are called exceptions, which is what this course is going to focus on: problems during runtime when Python attempts to execute syntactically correct Python code. There’s a lot of different built-in exceptions.
You’re going to get to know some of them, and there’s different ways of handling it with keywords that are built into Python as well. You’re going to get started on that in the next lesson, where you will learn how to raise your own exception in the same way that Python raised this
ZeroDivisionError for you in this example.
Become a Member to join the conversation.