» » » Python try-except- else vs finally with example program

  • For detail explanation of try and except block please check below link
  • Python try and except blocks with an example program
  • We will place all statements which are proved to generate exceptions in try block.
  • If any exception occurred then exception block will handle the exceptions.
  • If no exception raised in try block then except block wont be executed and else block will be executed.
  • In this scenario we might move the code from else to try block. If any exception raised in try block other statements in try block wont be executed and also else block will not be executed.
  • Finally block will always executes irrespective of any kind of exceptions.
  • So if we place any statements inside finally block of python script then those those statements will be executed for sure.
  • Else block will be executed when no exception occurred in try and finally will executes irrespective of any exception.
  • Lets see an example python program on try-except-else and try except-else-finally.




#1: Write a Python program which explains usage both else and finally blocks in python programming.

  1. #try_except with both else and finally blocks:
  2. string=input("enter some string: ")

  3. try:
  4.     x=string[5]
  5.     print("char at index 5 is: ",x)
  6.     print("no exception")
  7. except IndexError as e:
  8.     print("exception raised: ",e)
  9. else:
  10.     print("else block is executing becoz of no exception")
  11. finally:
  12.     print("finally block will always executes")


Output

  1. enter some string: python
  2. char at index 5 is:  n
  3. no exception
  4. else block is executing becoz of no exception
  5. finally block will always executes


python else vs python finally

Instance Of Java

We will help you in learning.Please leave your comments and suggestions in comment section. if you any doubts please use search box provided right side. Search there for answers thank you.
«
Next
This is the most recent post.
»
Previous
Older Post

No comments

Leave a Reply

Select Menu