Python exist exception Handling which more helpful in handling with error.
try excute the code which is inside the try block and if any error is found then then it return their respective error to the except block.
except block handle the error.
Syntaxtry: ................ ................ ................ except: ................ ................ ................Example
try: print(2/0) except: print("We cannot divide by zero")Output
We cannot divide by zero
Here we cannot divide 4 as 0 so except section is excute.
We can use more then one exception in one time.
try: print(2/0) except ZeroDivisionError: print("Zero Division Error") else: print("Error But Zero Division Error")Output
Zero Division Error
ZeroDivisionError
when we divide any number with zero then this zero occur.
NameError
occur when the error in name.
SyntaxError
occur when the error in syntax.
TypeError
occur when the error in type of variable like if we sum any character with number.
finally block are always execute.
try: print(2/0) except ZeroDivisionError: print("Zero Division Error") except: print("Error But Zero Division Error") finally: print("Finally always execute")Output
Zero Division Error Finally always execute
else block are execute if no error is occur.
try: print("No Error") except ZeroDivisionError: print("Zero Division Error") except: print("Error But Zero Division Error") else: print("There is no Error")Output
No Error There is no Error