参见英文答案 > Why is “except: pass” a bad programming practice? 16个
Python 2.7.5 (default, Feb 26 2014, 13:43:17)
[GCC 4.4.7 20120313 (Red Hat 4.4.7-4)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import sys
>>> try:
... sys.exit()
... except:
... print "in except"
...
in except
>>> try:
... sys.exit(0)
... except:
... print "in except"
...
in except
>>> try:
... sys.exit(1)
... except:
... print "in except"
...
in except
为什么我不能在try中触发sys.exit(),任何建议…… !!!
此处发布的代码包含所有版本详细信息.
我已经尝试了所有可能的方法来触发它,但我失败了.
它会变成’除’块.
提前致谢..
解决方法:
sys.exit()引发一个异常,即SystemExit.这就是你降落的原因.
看这个例子:
import sys
try:
sys.exit()
except:
print(sys.exc_info()[0])
这给你:
<type 'exceptions.SystemExit'>
虽然我无法想象有任何实际的理由这样做,你可以使用这个结构:
import sys
try:
sys.exit() # this always raises SystemExit
except SystemExit:
print("sys.exit() worked as expected")
except:
print("Something went horribly wrong") # some other exception got raised