Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

Python finally block example with program

  • Before discussing about finally block, please check our previous articles on try, except and else blocks. 
  • Basic python programs on try , except and else
  • As we already know about try like its duty is to find any exceptions if occurs and pass it to python except block so that except block will assign exception class object to handle exceptions.
  • Else will be executed if no exception occurs.
  • Finally block will executes even exceptions occurs. so in some situations we need to execute some statements compulsory even if any exceptions occurs in that scenario we will use python finally block
  • We will place all statements which would be executes irrespective of exceptions.
  • Lets see an example program on python finally block.
  • Python try except finally example
     



#1: Write a python program which explains usage of finally block in exception handling of python programming.

  1. try:
  2.   x = int(input("enter first number: "))
  3.   y = int(input("enter second number: "))
  4.   result=x/y
  5. except ArithmeticError as e:
  6.    print("cannot devide a number by zero: ", e)
  7. finally:
  8.    print("finally block")

Output
  1. enter first number: 10
  2. enter second number: 0
  3. cannot devide a number by zero:  division by zero
  4. finally block



This post first appeared on Java Tutorial - InstanceOfJava, please read the originial post: here

Share the post

Python finally block example with program

×

Subscribe to Java Tutorial - Instanceofjava

Get updates delivered right to your inbox!

Thank you for your subscription

×