Python编程中的异常处理、调试优化与C代码调用
1. 异常处理基础
在Python编程里,异常处理是一项关键技能。像 FileNotFoundError 这类异常,通过 __mro__ 属性可以查看其继承关系:
>>> FileNotFoundError.__mro__
(<class 'FileNotFoundError'>, <class 'OSError'>, <class 'Exception'>,
<class 'BaseException'>, <class 'object'>)
除 BaseException 外,上述列出的类都能与 except 语句配合使用。
1.1 捕获所有异常
若要编写能捕获所有异常的代码,可使用 Exception 作为异常处理器:
try:
...
except Exception as e:
...
log('Reason:', e)
不过,这种方式无法捕获 SystemExit 、 KeyboardInterrupt 和 GeneratorExit
超级会员免费看
订阅专栏 解锁全文

被折叠的 条评论
为什么被折叠?



