Python Handling Exceptions At Runtime
Python raises its own built-in exceptions when it detects an error in a program at runtime. You can use a try statement to catch and recover from an exception. You can also use except, else, finally and raise clauses to handle different types of exceptions.
An Exception is a condition that occurs during the execution of the program due to some reason and interrupts the execution. To handle exceptions in python we use try and except block. try block contains the code that needs to be executed and except block contains the code that will execute if some error occurred in the try block.
# Exception
a = 5
b = 0
print(a/b) # ZeroDivisionError: division by zero
# Exception Handling
try:
a = 5
b = 0
print(a/b)
except:
print("Can't Divide Number With 0")
# output Can't Divide Number With 0
If you have any questions about this code, you can drop a line in comment.
Comments
Post a Comment