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

Select a Random Element from a Stream

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

2 days ago

Estimate π Using Monte Carlo Method

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

3 weeks ago

Longest Substring with K Distinct Characters

Given an integer k and a string s, write a function to determine the length…

3 weeks ago

Staircase Climbing Ways

There is a staircase with N steps, and you can ascend either 1 step or…

4 weeks ago

Autocomplete System Implementation

Build an autocomplete system that, given a query string s and a set of possible…

4 weeks ago

Job Scheduler Implementation

Design a job scheduler that accepts a function f and an integer n. The scheduler…

4 weeks ago