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 – , 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 :
  #code to be executed - this code may executed successfully or may raise exception
  #code will get executed if exception raises in try block
  #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
    print("Try block executed successfully !!!")
    print("Exception occurred - here except block wont get executed ")
    print("We are done with first demo - finally block will executed always")
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

  numerator = 1
  denominator = 0
  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

  num1 = 23
  num2 = 43
Do not divide any number by zero

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: