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

Python try except example program

  • Exceptions are the objects representing the logical errors that occur at run time.
  • When python script encounters any error at run time it will create python object.
  • So we need to handle this situation otherwise python program will terminates because of that run time error ( Exception Object).
  • So we can handle this by assigning this python exception object to corresponding python class.
  • For that Python provides try and except blocks to handle exceptions.
  • In try block we need to keep all the statements which may raise exceptions at run time.
  • except block will catch that exception and assigns to corresponding error class.
  • Lets see an example python program on exception handling using try and except blocks.




#1: Example Program to handle Exception using try and except blocks in Python programming.

  1. #use of try_catch in functions:
  2. def f():
  3.    x=int(input("enter some number: "))
  4.    print(x)

  5. try:
  6.     f()
  7.     print("no exception")
  8. except ValueError as e:
  9.     print("exception: ", e)
  10.     print("Rest of the Application")

Output

  1. enter some number: 2
  2. 2
  3. no exception
  4. >>> 



  5. enter some number: "python"
  6. exception:  invalid literal for int() with base 10: '"python"'
  7. Rest of the Application
  8. >>> 



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

Share the post

Python try except example program

×

Subscribe to Java Tutorial - Instanceofjava

Get updates delivered right to your inbox!

Thank you for your subscription

×