I am new to python I am learning exception handling now.
try:
print(1/0)
int(input("number"))
import bala
except ZeroDivisionError:
print("Divided by zero")
except KeyboardInterrupt:
print("dont press ctrl C!")
except ValueError:
print("Value should be number")
except ModuleNotFoundError:
print("Module not found")
The above code exits after first exception and the rest of the try statements are not executed. Should I use separate try-except block for each statement? Like this
try:
int(input("number"))
except ValueError:
print("Value should be number")
and
try:
import bala
except ModuleNotFoundError:
print("Module not found")
If an exception is raised that makes Python stop the execution immediately. You can prevent a complete program stop by using a
tryandexcept. However if an exception is raised in thetryblock, it will still stop execution right there and only continue if an appropriateexceptblock catches the Exception (or if there is afinallyblock).In short: If you want to continue with the next statements you need to use separate
tryandexceptblocks. But if you want to execute the next statements only if the previous statements didn't raise an Exception you shouldn't use separatetryandexceptblocks.