Error handling in Python3

In Python, you can handle errors with exceptions. The following code will generate an FileNotFound error because the file it is trying to open does not exist:

fh = open('data.txt')
for strline in fh.readlines():
    print(strline)

output

FileNotFoundError: [Errno 2] No such file or directory: 'data.txt'

An error is generated and the program stop executing. Suppose, we want to program to continue because we will compensate for this error later in the code. We can use try: except:

try:
    fh = open('data.txt')
    for strline in fh.readlines():
        print(strline)
except:
    print('Error generated')
print('ignore and continue')

output

Error generated
continue regardless

If the code is try block generate an error, the action to be taken in response to this error is define in the except block. In this code, the error is caught is try and the action we defined is simply print and message and move one. If you come across this error while running a software, this error is not very helpful so let's write a more useful error.

try:
    fh = open('data.txt')
    for strline in fh.readlines():
        print(strline)
except IOError as err:
    print("Error generated in file open and print code: ({})".format(err)) 
print('ignore and continue')

output

Error generated in file open and print code: ([Errno 2] No such file or directory: 'data.txt')
ignore and continue