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:
try:
print("Hello world")
sum=2+6
finally:
# this block is always executed
# regardless of exception generation.
print('This is always executed')
Hello world
This is always executed
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')
You are dividing by zero
This is always executed
Here we are dividing a number by 0, hence except block executed.
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')
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
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
Staying up to the mark is what defines me. Hi all! I’m Rabecca Fatima a keen learner, great enthusiast, ready to take new challenges as stepping stones towards flying colors.
Problem Statement: Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses. Example…
Given an integer A. Compute and return the square root of A. If A is…
Given a zero-based permutation nums (0-indexed), build an array ans of the same length where…
A heap is a specialized tree-based data structure that satisfies the heap property. It is…
What is the Lowest Common Ancestor? In a tree, the lowest common ancestor (LCA) of…