异常处理

本章节中描述的函数将让您处理和引发 Python 异常。理解一些 Python 异常处理的基础知识很重要。它的工作原理有点像 POSIX errno 变量:最后发生的错误有全局指示器 (每线程)。大多数 C API 函数不会清零它当成功时,但会设置它以指示出错原因当失败时。大多数 C API 函数还返回错误指示器,通常是 NULL 若假设它们要返回指针,或者 -1 若它们返回整数 (例外: PyArg_* 函数返回 1 对于成功和 0 对于故障)。

Concretely, the error indicator consists of three object pointers: the exception’s type, the exception’s value, and the traceback object. Any of those pointers can be NULL if non-set (although some combinations are forbidden, for example you can’t have a non- NULL traceback if the exception type is NULL ).

当函数因调用的某个函数失败而必须失败时,一般不设置错误指示器;它调用的函数已有设置。它负责处理错误和清零异常或在清理它保持的任何资源后返回 (譬如:对象引用或内存分配);它应该 not 继续通常,若不准备处理错误。若由于错误而返回,重要的是向调用者指示有设置错误。若错误未被处理或被小心谨慎地传播,对 Python/C API 的额外调用可能没有如打算般的行为,且可能以神秘方式失败。

注意

错误指示器是 not 结果对于 sys.exc_info() 。前者相当于尚未被捕获的异常 (因此仍在传播),而后者返回被捕获后的异常 (因此已停止传播)。

打印和清零

void PyErr_Clear ( )
属于 稳定 ABI (应用程序二进制接口) .

清零错误指示器。若未设置错误指示器,则没有效果。

void PyErr_PrintEx ( int set_sys_last_vars )
属于 稳定 ABI (应用程序二进制接口) .

将标准回溯打印到 sys.stderr and clear the error indicator. 除非 the error is a SystemExit , in that case no traceback is printed and the Python process will exit with the error code specified by the SystemExit 实例。

Call this function only when the error indicator is set. Otherwise it will cause a fatal error!

set_sys_last_vars is nonzero, the variable sys.last_exc is set to the printed exception. For backwards compatibility, the deprecated variables sys.last_type , sys.last_value and sys.last_traceback are also set to the type, value and traceback of this exception, respectively.

3.12 版改变: The setting of sys.last_exc 被添加。