gpt4 book ai didi

python - 为什么在 except block 中调用 sys.exit(0) 后执行 finally block ?

转载 作者:IT老高 更新时间:2023-10-28 21:46:48 25 4
gpt4 key购买 nike

我是 Python 新手。我只想知道为什么 finally block 在 except block 中调用 sys.exit(0) 之后执行?

代码:

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()

顺便说一句,我只是想在 Java 中做同样的事情,其中​​ finally block 在 System.exit(0) 时 not 执行catch block 中。

最佳答案

全部 sys.exit()会引发 SystemExit 类型的异常.

来自 documentation :

Exit from Python. This is implemented by raising the SystemExitexception, so cleanup actions specified by finally clauses of trystatements are honored, and it is possible to intercept the exitattempt at an outer level.

如果你运行以下命令,你会自己看到:

import sys
try:
sys.exit(0)
except SystemExit as ex:
print 'caught SystemExit:', ex

作为替代方案,os._exit(n)使用状态码将停止进程绕过大部分清理,包括 finally block 等。

关于python - 为什么在 except block 中调用 sys.exit(0) 后执行 finally block ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7709411/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com