-->

Error and Exception Handling || finally

finally

The finally: block of code will always be run regardless if there was an exception in the try code block. The syntax is:

try:
    Code block here
    ...
    Due to any exception, this code may be skipped!
finally:
    This code block would always be executed.

For example:


try:
    f = open("testfile", "w")
    f.write("Test write statement")
    f.close()
finally:
    print("Always execute finally code blocks")

Always execute finally code blocks
We can use this in conjunction with except. Let's see a new example that will take into account a user providing the wrong input:

def askint():
    try:
        val = int(input("Please enter an integer: "))
    except:
        print("Looks like you did not enter an integer!")
    finally:
        print("Finally, I executed!")
    print(val)
askint()

OUTPUT

Please enter an integer: 5
Finally, I executed!
5
askint()

OUTPUT

Please enter an integer: five
Looks like you did not enter an integer!
Finally, I executed!
--------------------------------------------------------------------------- UnboundLocalError Traceback (most recent call last) <ipython-input-8-cc291aa76c10> in <module>() ----> 1 askint() <ipython-input-6-c97dd1c75d24> in askint() 7 finally: 8 print("Finally, I executed!") ----> 9 print(val) UnboundLocalError: local variable 'val' referenced before assignment

Notice how we got an error when trying to print val (because it was never properly assigned). Let's remedy this by asking the user and checking to make sure the input type is an integer:

def askint():
    try:
        val = int(input("Please enter an integer: "))
    except:
        print("Looks like you did not enter an integer!")
        val = int(input("Try again-Please enter an integer: "))
    finally:
        print("Finally, I executed!")
    print(val)
askint()

OUTPUT

Please enter an integer: five
Looks like you did not enter an integer!
Try again-Please enter an integer: four
Finally, I executed!
--------------------------------------------------------------------------- ValueError Traceback (most recent call last) >ipython-input-9-92b5f751eb01< in askint() 2 try: ----> 3 val = int(input("Please enter an integer: ")) 4 except: ValueError: invalid literal for int() with base 10: 'five' During handling of the above exception, another exception occurred: ValueError Traceback (most recent call last) <ipython-input-10-cc291aa76c10> in <module>() ----> 1 askint() <ipython-input-9-92b5f751eb01> in askint() 4 except: 5 print("Looks like you did not enter an integer!") ----> 6 val = int(input("Try again-Please enter an integer: ")) 7 finally: 8 print("Finally, I executed!") ValueError: invalid literal for int() with base 10: 'four'

Hmmm...that only did one check. How can we continually keep checking? We can use a while loop!

def askint():
    while True:
        try:
            val = int(input("Please enter an integer: "))
        except:
            print("Looks like you did not enter an integer!")
            continue
        else:
            print("Yep that's an integer!")
            break
        finally:
            print("Finally, I executed!")
        print(val)
askint()

OUTPUT

Please enter an integer: five
Looks like you did not enter an integer!
Finally, I executed!
Please enter an integer: four
Looks like you did not enter an integer!
Finally, I executed!
Please enter an integer: 3
Yep that's an integer!
Finally, I executed!

So why did our function print "Finally, I executed!" after each trial, yet it never printed val itself? This is because with a try/except/finally clause, any continue or break statements are reserved until after the try clause is completed. This means that even though a successful input of 3 brought us to the else: block, and a break statement was thrown, the try clause continued through to finally: before breaking out of the while loop. And since print(val) was outside the try clause, the break statement prevented it from running.

Let's make one final adjustment:

def askint():
    while True:
        try:
            val = int(input("Please enter an integer: "))
        except:
            print("Looks like you did not enter an integer!")
            continue
        else:
            print("Yep that's an integer!")
            print(val)
            break
        finally:
            print("Finally, I executed!")

OUTPUT

Please enter an integer: six
Looks like you did not enter an integer!
Finally, I executed!
Please enter an integer: 6
Yep that's an integer!
6
Finally, I executed!
Great! Now you know how to handle errors and exceptions in Python with the try, except, else, and finally notation!

Read Also

Post a Comment