In finally block we can handle closing of any open connections, files after the exception has been raised in the program or any additional steps to be performed prior to exiting the program.
Copy the below code into file expfinally.py and execute it or copy the code from GitHub
'''
Module demonstrates exception Handling
and finally keyword
'''
def ConvertToInteger(x):
''' ConvertToInteger function
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
'''
try:
num = int(x)
except:
errCode = -1
return errCode
finally:
print("finally block executed always with or without exception")
return num
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)
finally:
print("finally block executed always with or without exception")
For details on docstrings how to use help on module refer to chapter Docstrings and Comments in Python
We have used help on module to refer to the functions inside the module. Demonstrated finally keyword in case of exception and without exception.
expfinally.ConvertToInteger('a') error code of -1 is returned in case of exception and finally block is also executed.
expfinally.ConvertToInteger('29') a valid number is returned after conversion without exception and finally block is also executed.
No comments:
Post a Comment