Python 标准库

try...except

2022-09-22

捕获多个异常

将异常类型放入元组之中即可:

1
try:
2
...
3
except (URLError, ValueError):
4
log('Reason:', e)

捕获所有异常

1
try:
2
...
3
except Exception as e:
4
...
5
log('Reason:', e)

捕获除了 SystemExit 、 KeyboardInterrupt 和 GeneratorExit 之外的所有异常,如果需捕获这三个异常,可修改为:

1
try:
2
...
3
except BaseException as e:
4
...
5
log('Reason:', e)

参考