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

Generate Parenthesis | Intuition + Code | Recursion Tree | Backtracking | Java

Problem Statement: Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses. Example…

2 months ago

Square Root of Integer

Given an integer A. Compute and return the square root of A. If A is…

1 year ago

Build Array From Permutation

Given a zero-based permutation nums (0-indexed), build an array ans of the same length where…

1 year ago

DSA: Heap

A heap is a specialized tree-based data structure that satisfies the heap property. It is…

1 year ago

DSA: Trie

What is a Trie in DSA? A trie, often known as a prefix tree, is…

1 year ago

Trees: Lowest Common Ancestor

What is the Lowest Common Ancestor? In a tree, the lowest common ancestor (LCA) of…

1 year ago