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 sumbyzero():
try:
10/0
print "It will never print"
except Exception:
sys.exit(0)
print "Printing after exit"
finally:
print "Finally will always print"
sumbyzero()
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 type SystemExit
.
From the documentation :
Exit from Python. This is implemented by raising the
SystemExit
exception, so cleanup actions specified byfinally
clauses oftry
statements are honored, and it is possible to intercept the exit attempt at an outer level.
If you run the following, you'll see for yourself:
import sys
try:
sys.exit(0)
except SystemExit as ex:
print 'caught SystemExit:', ex
As an alternative, os._exit()
will stop the process bypassing much of the cleanup, including finally
blocks etc.
About your example:
A finally clause is always executed before leaving the try statement, whether an exception has occurred or not.
This is from Error and Exceptions part of Python docs. So - your finally block will always be executed in example you show unless you will use os._exit()
. But you should use it wisely...
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.