• 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. >>> 

try and except python example

Instance Of Java

We are here to help you learn! Feel free to leave your comments and suggestions in the comment section. If you have any doubts, use the search box on the right to find answers. Thank you! 😊
«
Next
Newer Post
»
Previous
Older Post

No comments

Leave a Reply

Select Menu