Why does try exits after first statement if it throws an Exception?

1.1k Views Asked by At

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")
3

There are 3 best solutions below

2
On BEST ANSWER

If an exception is raised that makes Python stop the execution immediately. You can prevent a complete program stop by using a try and except. However if an exception is raised in the try block, it will still stop execution right there and only continue if an appropriate except block catches the Exception (or if there is a finally block).

In short: If you want to continue with the next statements you need to use separate try and except blocks. But if you want to execute the next statements only if the previous statements didn't raise an Exception you shouldn't use separate try and except blocks.

0
On

You have to use multiple try/except blocks.

Once an error is found, anything happening is stopped, and the exception is dealed with.

Think of it as a fire. When there is a fire you stop whatever and run out. For python it deals with the exception

0
On

Yes you need to have separate exception blocks because if it gets by the first block, it thinks thats all it needs to get by, so if you want to test every one, you should use separate ones