python SystemExit
1
2
3
import sys
sys.exit(0) //
sys.exit(1) // 两者有什么区别,都会raise SystemExit Exception吗?

于是,做了一个小测试,结果让我有点傻眼。

1
2
3
4
5
6
7
try:
import sys
sys.exit(1)
except Exception as e:
print('hello exception')
// 居然没有答应出hello exception,考究了一下,sys.exit(),会raise SystemExit异常,可是这个SystemExit并不是派生自Exception,而是BaseException。而BaseException是Exception的父类。
// 所以会看到有一种说法,称之以上这种写法可以捕获,除与程序退出sys.exit()相关之外的所有异常。
1
2
3
4
5
6
try:
import sys
sys.exit(1) //
except:
print('hello exception')
// 结果打印出‘hello exception’,这种写法会捕获所有的exception,包含sys.exit,键盘中断和程序退出请求。如果在此处被捕获了,也就退不出去了。因此不建议这种写法。

回到开头的问题 sys.exit(0) 与 sys.exit(1) 的区别,都会raise SystemExit异常,但是区别在于程序的返回码。

sys.exit(0) 为正常退出,echo $?,结果为0

sys.exit(1) 为非正常退出,echo $, 结果为1

题外话:如何查看类的父类:

1
2
3
4
5
6
7
8
In [2]: Exception.__bases__
Out[2]: (BaseException,)

In [3]: SystemExit.__bases__
Out[3]: (BaseException,)

In [4]: IOError.__bases__
Out[4]: (Exception,)
Author: Chandler Kwok
Link: http://yoursite.com/2020/05/25/python-exception/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.