Sunday, October 25, 2020

Python Exception Handling

Exception break normal control flow of the program and terminate the program if not handled. Exceptions are errors raised during execution of program. Python generates exception for errors that are raised and can be handled using exception handling. Exception cause program to crash if not handled and prints the stack trace where and why exception has occurred.
Python uses try and except to handle exceptions within the program. The code or the operation that has possibility of raising an exception is written within the try block and the code to handle the exception raised in try block is written in except block.
For all below demonstration code can be downloaded from GitHub

At the REPL type the below commands to the get the current working directory,
import os
os.getcwd()  #This command will display the current working directory

Let us copy the below code to a file exception.py  and place the file in python current working directory to demonstrate exception handling.

''' Module Converts passed argument to Integer'''
def ConvertToInteger(x):
    num = int(x)
    return num

Now let us import the module exception.py in python REPL and see different exceptions raised.
When passed integer to our conversion function converted successfully. When we passed a character python raised 'ValueError' exception. After the exception program exited immediately.

Handling of Exceptions

Now we will see how to handle exception and ensure the program termination is smooth.
Lets update our current program to handle the exception in our code using try and except block.

''' Module Converts passed argument to Integer
    Args:
        Takes an argument and converts to Integer
    Return:
        Returns an integer number.
        In case of Exception error code -1 is returned
'''
def ConvertToInteger(x):
    try:
        num = int(x)
    except:
        errCode = -1
        return errCode
    return num

Let us run the program for the same input passed earlier and validate the output.


We have enclosed the code num = int(x)  raising exception in try and except block. When a character string is passed and cannot convert, python raised an exception and its handled in except block with error code -1.

Indentation Error, Syntax Error, Name Error are caused by programmer error these have to be fixed by programmer rather than at runtime of program.

Details of Exception Handled:
An exception has been raised and its handled, however we do not know the details of exception that is raised, let us print the details that caused the exception within our code.
We will read the file count the words in file to demonstrate exception details:

def CountWordsInfile(file):
    ''' CountWordsInfile function 
        Counts the total number of words in file
        Args:
            Takes a single argument fileName 
        Return:
            Return the number of words in the file
    '''

    try:
        fp = open(file, mode='rt', encoding='utf-8')
        data = fp.read()
        words = data.split()
        fp.close()
        print ("words in text file: ",len(words))
        return len(words)
    except Exception as error:
        print("Exception Occured and Exception is:")
        print(error)

Lets import the function CountWordsInfile from module exception and pass a random file that does not exist on the machine. Python prints the exception details.
Also let us pass a file that exists and see the output that prints the number of words in the file.

Code can be downloaded from GitHub
For file reading and writing files refer Python Reading Files




No comments:

Post a Comment

Operations on Python Dictionaries