coderz.py

Keep Coding Keep Cheering!

Python Exception Handling – II(Finally Keyword )

JOIN Clause
Finally Keyword 

Python has a finally keyword that is always executed after a try and except block. The finally block is always executed after the try block has terminated normally or due to an exception. Even if you return in the except block, the finally block will still be executed.

Note:

  • In Python, the keyword finally denotes the cleanup handler associated with a try block.
  • Finally, is an optional block. It is run after the associated except and else handlers have finished.
Example: without any exception
try:
    print("Hello world")
    sum=2+6
finally: 
        # this block is always executed  
        # regardless of exception generation. 
        print('This is always executed')  
Output:
Hello world
This is always executed
Example: with a defined exception
try:
        # Floor Division : Gives only Fractional
        # Part as Answer
        result = 7 // 0
except ZeroDivisionError:
        print("You are dividing by zero ")
else:
        print("Yeah ! Your answer is :", result)
finally: 
        # this block is always executed  
        # regardless of exception generation. 
        print('This is always executed')  
 
Output:
You are dividing by zero 
This is always executed

Here we are dividing a number by 0, hence except block executed.

Example: with an undefined exception
try:
        # Floor Division : Gives only Fractional
        # Part as Answer
        result = 7 // j
except ZeroDivisionError:
        print("Sorry ! You are dividing by zero ")
else:
        print("Yeah ! Your answer is :", result)
finally: 
        # this block is always executed  
        # regardless of exception generation. 
        print('This is always executed')  
 
Output:
This is always executed
Traceback (most recent call last):
  File "<string>", line 4, in <module>
NameError: name 'j' is not defined

Here we are dividing a number with a string value. Because we did not handle the ValueError exception, our code will halt the execution, and an exception will be thrown, but the code in the finally block will still be executed.

Note: also read about Python Exception Handling – I

Follow Me

Please follow me to read my latest post on programming and technology if you like my post.

https://www.instagram.com/coderz.py/

https://www.facebook.com/coderz.py

Leave a Comment

Your email address will not be published. Required fields are marked *

Advertisement