Learn practical skills, build real-world projects, and advance your career

Understanding Errors and Exceptions in Python

alt

One of the most common situations while writing code is getting stuck on an unidentifiable error. In such a case, python's ecosystem helps us to trace back our function calls with the help of traceback reports, to find out the exception raised.

Imgur

These tracebacks return the exception name and the error message along with the executed code to help us identify the reason for these exceptions being raised.

Exceptions raised simply define the type of error our program has run into. Which is why these terms are used interchangeably, but precisely mean the same.

There are a number of built-in exceptions in python library, who's awareness can help to speed up the our programming. Let's look at some of the important buit-in exceptions in python.

SyntaxError

The most common type of error in a Python program is when the user uses incorrect syntax. i.e, when a piece of code is not in accordance with its documentation.

In the code below, the variable a has been declared with its desired data type stated before the variable name, which is not how a variable is declared in Python.

int a = 2.8
a
File "<ipython-input-1-14f5aded83ca>", line 1 int a = 2.8 ^ SyntaxError: invalid syntax

The error message apprises us that there was an error in our syntax. Delving into the traceback, there is a ^ Caret symbol, that points out the location of incorrect code which caused the exception .

# Correct Code:
a = int(2.8)
a
2