Errors and Exception Handling in Python

Exception and Error Handling in Python with Real Life Examples
Written by Paayi Tech |11-Apr-2019 | 0 Comments | 201 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 with errors in code. In programming languages there are two type of error, following are the name of errors:

  1. Syntax Error
  2. Exceptions

 

Syntax Error:

Syntax error are those errors which are generated because of writing wrong code. They are also called parsing error. In background of any programming language there is a parser which distinguish 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.

 

As we can see in the above snippet there is a syntax error which states invalid syntax. This is generated because we have not put the colon at the end of the for 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 the figure 2:

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

 

Some Other Syntax Error:

In python if proper indentation is not followed than it generates the syntax error. It is a protocol to give four spaces in new line when colon is given as in case of for, while, function and classes. As the following snippet show we have not provided the 4 spaces indentation in new line after the of 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 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 EOF syntax error.

 

 

Exceptions:

Even the code is syntactically correct still there is a possibility the code can cause an error. Errors that are detected during the execution are called an exception. Exception are not fatal, we can handle it easily. The exceptions are lot of type. 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 type cast 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 a 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 first scenario we have defined a variable after the print statement and in second scenario we saw Error because it will not find any variable that is name as “age”. 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 the zero. In 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 scenario where a user can input wrong values. For example, a user can click login button without even writing a credentials or write the string where numbers are required in such scenarios our application crashed and a user have 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 an 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 except 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 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. By pass we can pass the error and continue looping and similar thing can be done by continue keyword.

 

Finally:

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

Code
for i in range (5):
    try:
        value = float (input ("Enter the float value"))
    except:
        pass
 
    finally:
        print ("done loop "+str(i+1))

 

 

 

This is the basics of exceptions. It will be used more when using servers and fetching data online. We will see its use in higher level.

 

 





Login/Sign Up

Comments




Related Posts



© Copyright 2019, 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.