Python Tutorials: Errors and Exception Handling in Python

Python Tutorials: Learn Python Exception and Error Handling with Real Life Examples
Written by Paayi Tech |20-Oct-2020 | 0 Comments | 2114 Views

From the start of the course, if you have code by yourself and made some changes by tweaking the code, you may come across errors in code. In programming languages, there are two types of error, the following are the name of errors:

  1. Syntax Error
  2. Exceptions


Syntax Error:

Syntax errors are those errors that are generated because of writing the wrong code. They are also called parsing error. In the background of any programming language, there is a parser that distinguishes the keywords and variables to execute the program.

We cannot code by our own will. The protocols are defined, and we have to copy similar as it is; otherwise, the program will crash and give us syntax error.

error-exception-image-python python tutorials


As we can see in the above snippet, there is a syntax error that states invalid syntax. This is generated because we have not put the colon at the end of the loop and putting the colon after for loop, while loop, function, and classes are in the defined protocols of python programming language. Syntax errors are generated before the program execution.  This error can be resolved by writing the colon after for loop as shown in figure 2:


In the second line, we can see that there is no error; we just write the colon symbol after the end of for loop.


Some Other Syntax Error:

In python, if proper indentation is not followed, then it generates the syntax error. It is a protocol to give four spaces in a new line when the colon is given as in case of for, while, function, and classes. As the following snippet show, we have not provided the four spaces indentation in a new line after the while loop.



This code generates the syntax error for indentation as following:


The error clearly says that expected an indented block, and in code, the position is highlighted where we have made a mistake.


Error on Line EOL:


If we forgot to close the strings properly than the compiler will generate the syntax error as Shown in the above snippet.


End of File EOF:

EOF is another type of syntax error in which the brackets are not properly closed. Figure 6 is an example of an EOF syntax error.




Even the code is syntactically correct; there is still a possibility the code can cause an error. Errors that are detected during the execution are called an exception. An exception is not fatal; we can handle it easily. The exceptions are a lot of types. There may be an exception of ZeroDivision, NameError, TypeError, bad frame while reading the input from the live camera feed, etc. Following are some of the example of exception:




age = 25

print ("My age is "+age+" years old")


As we see, there is nothing wrong with the code. The syntax is right, we have followed all the protocols to write the code, but the code will give the type error on execution. This is because we cannot concatenate the string with an integer. We first have to typecast an integer to string. The error that is generated is as follows


Traceback (most recent call last):

  File "/home/lalatoofani/", line 2, in

    print ("My#Error age is "+age+" years old")

TypeError: must be str, not int


The right way to execute the above code is following:


age = 25

print ("My age is "+str(age)+" years old")


Name Error:

Name error is generated when the variable is not assigned or not in the scope of that body than compiler gives you name error as following.

#Code 1

print ("My age is "+str(age)+" years old")

age = 25

#Code 2

print ("My age is "+str(age)+" years old")

 In the first scenario, we have defined a variable after the print statement, and in the second scenario, we saw error because it will not find any variable that is named as “age.” The following error will be generated.



Traceback (most recent call last):

  File "/home/lalatoofani/", line 2, in

    print ("My age is "+str(age)+" years old")

NameError: name 'age' is not defined


Zero Division Error:

We all know that nothing can be divided by zero. In a normal calculator, it will give an error of value is infinite. But in python, I will generate the ZeroDivision Error. Figure 7 below shows zero division error:




Error Handling:

In normal life scenarios, there are lots and lots of scenarios where a user can input wrong values. For example, a user can click the login button without even writing credentials or write the string where numbers are required. In such scenarios, our application crashed, and a user has to start again without knowing what happens in the background. For such scenarios, it is compulsory to handle an error, and this can be done by making try/ except block. Following way to make a try-except block:


while True:


        value = float (input ("Enter the float value"))


        print ("The value is wrong")


The above code will take input like 2.0,4.5 etc. If a string is passed into it, it will make an exception. If we don’t make an exception, the code will crash, but in this case, the program will not crash and continue to run.

The output of the following code is as follows:



Now, we will know what these blocks do:

Try Block:

Try block will run the code. For example, if a try block is in a while loop, the program will be iterated repeatedly. If the program receives non-desirable input, it will go to the except block.



This block will throw out the exception. If a user wants to print a message of exception, this will be done in except block. Bypass, we can pass the error and continue looping, and a similar thing can be done by continue keyword.



Finally, the block is always executed. This is because we can write the remaining code in a final block.


for i in range (5):


        value = float (input ("Enter the float value"))





        print ("done loop "+str(i+1))




These are the basics of exceptions. It will be used more when using servers and fetching data online. We will see its use at a higher level.



Login/Sign Up


Related Posts

© Copyright 2020, All Rights Reserved.

This site uses cookies. By continuing to use this site or clicking "I Agree", you agree to the use of cookies. Read our cookies policy and privacy statement for more information.