Categories: python

Python Exception Handling – II(Finally Keyword )

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

Recent Posts

Find Intersection of Two Singly Linked Lists

You are given two singly linked lists that intersect at some node. Your task is…

59 minutes ago

Minimum Cost to Paint Houses with K Colors

A builder plans to construct N houses in a row, where each house can be…

3 days ago

Longest Absolute Path in File System Representation

Find the length of the longest absolute path to a file within the abstracted file…

3 weeks ago

Efficient Order Log Storage

You manage an e-commerce website and need to keep track of the last N order…

1 month ago

Select a Random Element from a Stream

You are given a stream of elements that is too large to fit into memory.…

1 month ago

Estimate π Using Monte Carlo Method

The formula for the area of a circle is given by πr². Use the Monte…

2 months ago