I’m new to Python. I just want to know why the finally block is executing after calling sys.exit(0) in the except block?
Code:
import sys
def divide_by_zero():
try:
10/0
print "It will never print"
except Exception:
sys.exit(0)
print "Printing after exit"
finally:
print "Finally will always print"
divide_by_zero()
Btw., I was just trying to do the same thing as in Java, where the finally block is not executed when System.exit(0) is in the catch block.
All
sys.exit()does is raise an exception of typeSystemExit.From the documentation:
If you run the following, you’ll see for yourself:
As an alternative,
os._exit(n)with the status code will stop the process bypassing much of the cleanup, includingfinallyblocks etc.