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

Python try except else with example program

  • 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")

Output

  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  




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

Share the post

Python try except else with example program

×

Subscribe to Java Tutorial - Instanceofjava

Get updates delivered right to your inbox!

Thank you for your subscription

×