Python : Finally block

Hello Friends,

As we are discussing exception handling in Python, today we will continue to discuss finally block

If you didn’t got chance to look my previous article on exception handling on Python – https://knowledge-junction.in/2022/03/19/exception-handling-in-python , please have a look once

Take away from this article:

  • Understand finally block
  • Couple of demos / examples

What is finally block?

  • finally block is block which is always executed after try and except block
  • finally block is always executed whether try block executed successfully or raises an exception
  • Syntax :
try:
  #code to be executed - this code may executed successfully or may raise exception
except:
  #code will get executed if exception raises in try block
finally:
  #code will be executed irrespective of exception raised in try block or not

  • finally block is mostly used to clean up the resources used. For example – to close the file OR to close the objects

Demo 1 – Code in try block executes successfully and code in finally block get executed

#this is program to demonstrate successful execution of try and finally block
try:
    print("Try block executed successfully !!!")
except:
    print("Exception occurred - here except block wont get executed ")
finally:
    print("We are done with first demo - finally block will executed always")
-------------------------------------------------------------------
Output
Try block executed successfully !!!
We are done with first demo - finally block will executed always

Demo 2 : Try block raises an exception, exception block get executed and then finally block executed

# Program to show how finally block is executed after exception raises

try:
  numerator = 1
  denominator = 0
  print(numerator/denominator)
except:
  print("Do not divide any number by zero")


# After printing the statement "Do not divide any number by zero" 
# The program will be exited so to execute the next set of code we will use finally block

finally:
  num1 = 23
  num2 = 43
  print(num1*num2)
--------------------------------------------------------------------
Output 
Do not divide any number by zero
989

Thanks for reading! If you have any suggestions / questions please feel free to discuss !

You may also like...

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: