Exception handling with try, except, else, and finally
- Try: This block will test the excepted error to occur
- Except: Here you can handle the error
- Else: If there is no exception then this block will be executed
- Finally: Finally block always gets executed either exception is generated or not
Try, Except, else and Finally in Python
An Exception is an Unexpected Event, which occurs during the execution of the program. It is also known as a run time error. When that error occurs, Python generates an exception during the execution and that can be handled, which prevents your program from interrupting.
Example: In this code, The system can not divide the number with zero so an exception is raised.
Python3
a = 5 b = 0 print (a / b) |
Output
Traceback (most recent call last):
File "/home/8a10be6ca075391a8b174e0987a3e7f5.py", line 3, in <module>
print(a/b)
ZeroDivisionError: division by zero