Syntax Errors vs Exceptions in Python

Rizwan Qaiser
Sep 1, 2018 · 2 min read

The following content will be covered:

  • Syntax Errors and Exceptions

Understanding Syntax Errors vs. Exceptions

Syntax Errors

Syntax errors are perhaps the most common kind of complaint you get while you are still learning Python. Example:

>>> while True print('Hello world')
File "<stdin>", line 1
while True print('Hello world')
^
SyntaxError: invalid syntax

Python returns the offending line and displays a little ‘arrow’ pointing at the earliest point in the line where the error was detected.

The error is caused by (or at least detected at) the function, command, or token preceding the arrow.

In the example above, the error is detected at the function print(), since a colon (':') is missing before theprint()function and after the while Truestatement. File name and line number are also printed so you know where to look in case the input came from a script.

Exceptions

Even if a statement or expression is syntactically correct, it may cause an error when an attempt is made to execute it.

Errors detected during code execution are called exceptions and are not unconditionally fatal. Most exceptions are not handled by programs, however, and result in error messages as shown here:

>>> 10 * (1/0)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ZeroDivisionError: division by zero>>> 4 + spam*3
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'spam' is not defined>>> '2' + 2
Traceback (most recent call last):
File "<stdin>", line 1, in <module>

TypeError: Can't convert 'int' object to str implicitly

The last line of the error message indicates what happened. Here you see three different exceptions and the type is printed as part of the message. The types in the example are ZeroDivisionError, NameError and TypeError.

The string that denotes the exception type is built into the language.This is true for all built-in exceptions, but need not be true for user-defined exceptions (although it is a useful convention). The rest of the line provides detail based on the type of exception and what caused it.

The preceding part of the error message shows the context where the exception happened in the form of a “traceback”.

Here you can find a list of Built-in Exceptions and their meanings.

Rizwan Qaiser

Written by

Architecting analytical solutions.

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade