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:

error-exception-image-python-image2.PNG

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.

error-exception-image-python-image3.PNG

 

This code generates the syntax error for indentation as following:

error-exception-image-python-image4.PNG

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:

error-exception-image-python-image5.PNG

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.

error-exception-image-python-image6.PNG

 

Exceptions:

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:

 

TypeError:

#Code

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

#Error

Traceback (most recent call last):

  File "/home/lalatoofani/PythonProgramming.py", 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:

#Code

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.

 

#Error

Traceback (most recent call last):

  File "/home/lalatoofani/PythonProgramming.py", 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-exception-image-python-image7.PNG

 

 

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:

Code

while True:

    try:

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

    except:

        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:

error-exception-image-python-image8.PNG

 

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.

 

Except:

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:

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

Code

for i in range (5):

    try:

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

    except:

        pass

 

    finally:

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

 

 

error-exception-image-python-image9.PNG

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

Comments




Related Posts



© Copyright 2020, All Rights Reserved. paayi.com

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.