• Please read below post to get an idea of try and except blocks in detail
  • Python try except example program
  • We will place all statements which are proven to generate exceptions in try block so that if any error occurred it will immediately enters into except and assign exception object to corresponding class.
  • If any exception occurs in try then except will be executed in order to handle the exception.
  • If no exception occurred in the try the it will executes else block.
  • So in Python exception handing else block will be executed if and only if no exceptions are occurred in try block and all the statements in try executed.
  • Lets see an example program on how can we use else in python exception handling
  • try-except-else 

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

  1. try:
  2.     x = int(input("enter 1st number: "))
  3.     y = int(input("enter 2nd number: "))
  4.     print(x/y)
  5.     string=input("enter some string: ")
  6.     print(string[8])
  7. except (IndexError, ZeroDivisionError) as e:
  8.     print("An error occurred :",e)
  9. else:
  10.     print("no error")


  1. enter 1st number: 2
  2. enter 2nd number: 0
  3. An error occurred : division by zero

  4. enter 1st number: 2
  5. enter 2nd number: 1
  6. 2.0
  7. enter some string: python
  8. An error occurred : string index out of range

  9. enter 1st number: 2
  10. enter 2nd number: 1
  11. 2.0
  12. enter some string: python is very easy
  13. s
  14. no error  

python else example program

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.
Newer Post
Older Post

No comments

Leave a Reply

Select Menu