- 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.
- #use of try_catch in functions:
- def f():
- x=int(input("enter some number: "))
- print(x)
- try:
- f()
- print("no exception")
- except ValueError as e:
- print("exception: ", e)
- print("Rest of the Application")
Output
- enter some number: 2
- 2
- no exception
- >>>
- enter some number: "python"
- exception: invalid literal for int() with base 10: '"python"'
- Rest of the Application
- >>>
No comments