PadhaiTime Logo
Padhai Time

Exception Handling in Python

While processing the data, we may often face errors. Either there can be some issues with the data format or the operation which we are applying may not be valid. In either of the cases, we need a proper exception handling mechanism which can easily pinpoint the erroneous statement so that we can work on it and fix them for future.

 

Before we deep dive into Exception Handling part, let us just check out what kind of errors can occur in an application:

 

1) Syntax Errors: These are the errors which we make while writing the code. When we forget or miss the right syntax, in those cases we get syntax error.

 

Example 1:

 import pandas as pd
 df = pd.DataFrame(}

Output:

File "<ipython-input-5-90d726292a59>", line 2
    df = pd.DataFrame(}
                      ^
SyntaxError: closing parenthesis '}' does not match opening parenthesis '('

 

Example 2:

 if 2 == 3:
 print(3)

Output:

File "<ipython-input-7-f3958dc05e2e>", line 2
    print(3)
    ^
IndentationError: expected an indented block

 

Generally, you can figure out these mistakes before running your code. There are some IDEs like Pycharm, Jupyter Notebook which highlight the erroneous statements beforehand.

 

2) Logical Errors: These are the logical mistakes that we make while writing the code. The code may not contain any syntax error, but the logic that we have written is not valid and contains some bugs in it.

 

Example:

Total_marks = exam1 + exam2 + exam3 + exam4 + exam5 / 5

Above logic is correct syntactically and will not throw any error, but the logic is incorrect. These are the manual mistakes/bugs left in the code. These can be resolved by reviewing the code by yourself or raising a pull request with your peers for review.

 

3) Exceptions: These are the failures happening during run time. Either there is some logical error in your code which has led to this exception or there is something different with data / system due to which your code is not performing as expected. In either of these situations, the first thing will be to report this issue by catching in run time and later fixing the erroneous parts / statements.

 

There are different types of exceptions which can occur:

Types of Exceptions:

  • ZeroDivisionError
  • KeyError
  • FileNotFoundError 
  • IndexError 
  • MemoryError
  • TimeoutError
  • Any other Exception

For exception handling, keywords that we use are “try” and “except

 

Syntax:

	try:
		Statements for which you want to catch exception reside here
        except:
               exception handling statements

Note: if an exception occurs inside a try block, control will be redirected to the except block and later statements in try will remain unexecuted.

Now let us understand how to catch an exception in run time.

 

1) Zero Division Error: When a number gets divided by 0, then this exception occurs.

How to Catch?

Code:

try:
    num_value = 5
    denom_value = 0
    result = num_value / denom_value
    print("Finished without error")
    
except ZeroDivisionError as e:
    print("Zero Division Error caught and the Exception is:", e)

Output:

Zero Division Error caught and the Exception is: division by zero

How to Fix?

Code:

try:
    num_value = 5
    denom_value = 0
    if denom_value > 0:
        result = num_value / denom_value
    else:
        result = 0 # some default value
    print("Finished without error")
    
except ZeroDivisionError as e:
    print("Zero Division Error caught and the Exception is:", e)

Output:

Finished without error 

 

2) Key Error: When we are referring to some key in a dictionary but it does not exists, then this exception occurs.

How to Catch?

Code:

try:
    dict_var = {"Gender": "Male", "Age": 45}
    age = dict_var['Age']
    salary = dict_var['Salary']
    print("Finished without error")
    
except KeyError as e:
    print("Key Error caught and the Exception is:", e)

Output:

Key Error caught and the Exception is: 'Salary' 

  

How to Fix?

Code:

try:
    dict_var = {"Gender": "Male", "Age": 45}
    
    if "Age" in dict_var.keys():
        age = dict_var['Age']
    else:
        age = -9999 # Some default value

    if "Salary" in dict_var.keys():
        Salary = dict_var['Salary']
    else:
        salary = -9999 # Some default value

    print("Finished without error")
    
except KeyError as e:
    print("Key Error caught and the Exception is:", e)

Output:

Finished without error 

 

3) File Not Found Error: This exception occurs when the file name specified for reading is not correct. Either the folder location is not correct or the file doesn’t exists in that folder.

How to Catch?

Code:

try:
    df = pd.read_csv("filename.csv")
    print("Finished without error")
    
except FileNotFoundError as e:
    print("FileNotFoundError caught and the Exception is:", e)

Output:

FileNotFoundError caught and the Exception is: [Errno 2] No such file or directory: 'filename.csv' 

 

How to Fix?

Code:

Specify the right location for your file and it should work properly. 

try:
    df = pd.read_csv("documents/filename.csv")
    print("Finished without error")
    
except FileNotFoundError as e:
    print("FileNotFoundError caught and the Exception is:", e)

Output:

Finished without error

 

4) Index Error: When we are referring to some index which does not exist then this Index Error occurs.

Suppose one list has just 4 items and their index will range from 0 to 3, but if we are printing the item on the 4th index, then the exception occurs because there is no such element residing on that location.

How to Catch?

try:
    items = ["India", "US", "China", "Russia"]
    index = 4
    
    #Index is 4, whereas list contains only 4 items whose index vary from 0 to 3 only
    print(items[index])  
    print("Finished without error")

except IndexError as e:
    print("IndexError caught and the Exception is:", e)

Output:

IndexError caught and the Exception is: list index out of range 

 

How to Fix?

try:
    items = ["India", "US", "China", "Russia"]
    index = 4
    if index < len(items):  
        print(items[index])
    else:
        print("Index is not correct")
    print("Finished without error")

except IndexError as e:
    print("IndexError caught and the Exception is:", e)

Output:

Index is not correct
Finished without error
 

 

5) Memory Error: When you are loading a heavy file but your RAM is low, then the file reading gets interrupted with Memory Error. 

To handle this, you can read the file in two ways:

a) By reading only the chunks of rows instead of all

b) By reading few columns instead of all

 

6) Timeout Error: When we hit some api to fetch data, and if the api is taking too long or maybe if the api is down, then the request gets timed out. As each request has some time associated until then it waits for the response, if the wait time exceeds, the request fails with Timeout Error.

How to fix it?

Check if you have proper Internet Connection.
Check if you have access to that API
Check if you are passing right set of parameters to it
Check if API is LIVE and running from backend

 

7) Catch any type of Exception: So far we have discussed the specific types of exception that occur in your application and how to catch them, but it is difficult for you to write catch statement for all the types of exception. Hence there comes a general Exception clause which helps us to catch any type of Exception that is occurring in the application. The exceptions which we have discussed above can also be caught by this General Exception clause. Let us just check this out.

How to Catch?

Code:

try:
    df = pd.read_csv("documents/filename.csv")
    print("File reading is succesful")
    
    items = ["India", "US", "China", "Russia"]
    index = 2
    if index < len(items):  
        print("Correctly fetched the item", items[index])
    else:
        print("Index is not correct")

    num_value = 5
    denom_value = 0
    result = num_value / denom_value
    print("Finished without error")
    
except IndexError as e:
    print("IndexError caught and the Exception is:", e)

except Exception as e:
    print("Exception Occured:", e)

Output:

File reading is succesful
Correctly fetched the item China
Exception Occured: division by zero

  

That is pretty much it, We hope you get the idea about the types of error that can occur in your application and how to fix them.

 

Bengaluru, India
contact.padhaitime@gmail.com
  • We collect cookies and may share with 3rd party vendors for analytics, advertising and to enhance your experience. You can read more about our cookie policy by clicking on the 'Learn More' Button. By Clicking 'Accept', you agree to use our cookie technology.
    Our Privacy policy can be found by clicking here