While writing code and running it we halt due to some run time errors and exceptions,so
How to handle those exceptions in python and in how many ways we can handle them...
Any answer will be of great help......
As Jaanvi is saying, use try .. except.
There are cases where if .. else might work too, but try .. except is a better option, I think.
Let's say you want to devide 2 numbers. In this case you might get ZeroDivisionError.
a = 10
b = 0
# for a / b will generate a ZeroDivisionError on runtime
# to prevent the crash:
try:
res = a / b
except ZeroDivisionError e:
# for negative value you will get -inf
# for positive value you will get inf
res = a * float('inf')
# print the error, if you want to see it
print(e)
except:
# this will catch any remaining errors
print('Other errors')
You can read more here: (https://www.idkrtm.com/error-handling-in-python-using-with-and-try/)
Use try and except methods:
try:
...................
.......
...your code
..
except:
...to capture errors...