例外處理¶
The functions described in this chapter will let you handle and raise Python
exceptions. It is important to understand some of the basics of Python
exception handling. It works somewhat like the POSIX errno variable:
there is a global indicator (per thread) of the last error that occurred. Most
C API functions don't clear this on success, but will set it to indicate the
cause of the error on failure. Most C API functions also return an error
indicator, usually NULL if they are supposed to return a pointer, or -1
if they return an integer (exception: the PyArg_* functions
return 1 for success and 0 for failure).
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).
When a function must fail because some function it called failed, it generally doesn't set the error indicator; the function it called already set it. It is responsible for either handling the error and clearing the exception or returning after cleaning up any resources it holds (such as object references or memory allocations); it should not continue normally if it is not prepared to handle the error. If returning due to an error, it is important to indicate to the caller that an error has been set. If the error is not handled or carefully propagated, additional calls into the Python/C API may not behave as intended and may fail in mysterious ways.
備註
The error indicator is not the result of sys.exc_info().
The former corresponds to an exception that is not yet caught (and is
therefore still propagating), while the latter returns an exception after
it is caught (and has therefore stopped propagating).
Printing and clearing¶
-
void PyErr_Clear()¶
- 為 穩定 ABI 的一部分.
Clear the error indicator. If the error indicator is not set, there is no effect.
-
void PyErr_PrintEx(int set_sys_last_vars)¶
- 為 穩定 ABI 的一部分.
Print a standard traceback to
sys.stderrand clear the error indicator. Unless the error is aSystemExit, in that case no traceback is printed and the Python process will exit with the error code specified by theSystemExitinstance.Call this function only when the error indicator is set. Otherwise it will cause a fatal error!
If set_sys_last_vars is nonzero, the variable
sys.last_excis set to the printed exception. For backwards compatibility, the deprecated variablessys.last_type,sys.last_valueandsys.last_tracebackare also set to the type, value and traceback of this exception, respectively.在 3.12 版的變更: 新增
sys.last_exc設定。
-
void PyErr_Print()¶
- 為 穩定 ABI 的一部分.
PyErr_PrintEx(1)的別名。
-
void PyErr_WriteUnraisable(PyObject *obj)¶
- 為 穩定 ABI 的一部分.
Call
sys.unraisablehook()using the current exception and obj argument.This utility function prints a warning message to
sys.stderrwhen an exception has been set but it is impossible for the interpreter to actually raise the exception. It is used, for example, when an exception occurs in an__del__()method.The function is called with a single argument obj that identifies the context in which the unraisable exception occurred. If possible, the repr of obj will be printed in the warning message. If obj is
NULL, only the traceback is printed.An exception must be set when calling this function.
在 3.4 版的變更: Print a traceback. Print only traceback if obj is
NULL.在 3.8 版的變更: 使用
sys.unraisablehook()。
-
void PyErr_FormatUnraisable(const char *format, ...)¶
Similar to
PyErr_WriteUnraisable(), but the format and subsequent parameters help format the warning message; they have the same meaning and values as inPyUnicode_FromFormat().PyErr_WriteUnraisable(obj)is roughly equivalent toPyErr_FormatUnraisable("Exception ignored in: %R", obj). If format isNULL, only the traceback is printed.在 3.13 版被加入.
-
void PyErr_DisplayException(PyObject *exc)¶
- 為 穩定 ABI 的一部分 自 3.12 版本開始.
Print the standard traceback display of
exctosys.stderr, including chained exceptions and notes.在 3.12 版被加入.
引發例外¶
These functions help you set the current thread's error indicator.
For convenience, some of these functions will always return a
NULL pointer for use in a return statement.
-
void PyErr_SetString(PyObject *type, const char *message)¶
- 為 穩定 ABI 的一部分.
This is the most common way to set the error indicator. The first argument specifies the exception type; it is normally one of the standard exceptions, e.g.
PyExc_RuntimeError. You need not create a new strong reference to it (e.g. withPy_INCREF()). The second argument is an error message; it is decoded from'utf-8'.
-
void PyErr_SetObject(PyObject *type, PyObject *value)¶
- 為 穩定 ABI 的一部分.
This function is similar to
PyErr_SetString()but lets you specify an arbitrary Python object for the "value" of the exception.
-
PyObject *PyErr_Format(PyObject *exception, const char *format, ...)¶
- 回傳值:總是為 NULL。 為 穩定 ABI 的一部分.
This function sets the error indicator and returns
NULL. exception should be a Python exception class. The format and subsequent parameters help format the error message; they have the same meaning and values as inPyUnicode_FromFormat(). format is an ASCII-encoded string.
-
PyObject *PyErr_FormatV(PyObject *exception, const char *format, va_list vargs)¶
- 回傳值:總是為 NULL。 為 穩定 ABI 的一部分 自 3.5 版本開始.
Same as
PyErr_Format(), but taking ava_listargument rather than a variable number of arguments.在 3.5 版被加入.
-
void PyErr_SetNone(PyObject *type)¶
- 為 穩定 ABI 的一部分.
This is a shorthand for
PyErr_SetObject(type, Py_None).
-
int PyErr_BadArgument()¶
- 為 穩定 ABI 的一部分.
This is a shorthand for
PyErr_SetString(PyExc_TypeError, message), where message indicates that a built-in operation was invoked with an illegal argument. It is mostly for internal use.
-
PyObject *PyErr_NoMemory()¶
- 回傳值:總是為 NULL。 為 穩定 ABI 的一部分.
This is a shorthand for
PyErr_SetNone(PyExc_MemoryError); it returnsNULLso an object allocation function can writereturn PyErr_NoMemory();when it runs out of memory.
-
PyObject *PyErr_SetFromErrno(PyObject *type)¶
- 回傳值:總是為 NULL。 為 穩定 ABI 的一部分.
This is a convenience function to raise an exception when a C library function has returned an error and set the C variable
errno. It constructs a tuple object whose first item is the integererrnovalue and whose second item is the corresponding error message (gotten fromstrerror()), and then callsPyErr_SetObject(type, object). On Unix, when theerrnovalue isEINTR, indicating an interrupted system call, this callsPyErr_CheckSignals(), and if that set the error indicator, leaves it set to that. The function always returnsNULL, so a wrapper function around a system call can writereturn PyErr_SetFromErrno(type);when the system call returns an error.
-
PyObject *PyErr_SetFromErrnoWithFilenameObject(PyObject *type, PyObject *filenameObject)¶
- 回傳值:總是為 NULL。 為 穩定 ABI 的一部分.
Similar to
PyErr_SetFromErrno(), with the additional behavior that if filenameObject is notNULL, it is passed to the constructor of type as a third parameter. In the case ofOSErrorexception, this is used to define thefilenameattribute of the exception instance.
-
PyObject *PyErr_SetFromErrnoWithFilenameObjects(PyObject *type, PyObject *filenameObject, PyObject *filenameObject2)¶
- 回傳值:總是為 NULL。 為 穩定 ABI 的一部分 自 3.7 版本開始.
Similar to
PyErr_SetFromErrnoWithFilenameObject(), but takes a second filename object, for raising errors when a function that takes two filenames fails.在 3.4 版被加入.
-
PyObject *PyErr_SetFromErrnoWithFilename(PyObject *type, const char *filename)¶
- 回傳值:總是為 NULL。 為 穩定 ABI 的一部分.
Similar to
PyErr_SetFromErrnoWithFilenameObject(), but the filename is given as a C string. filename is decoded from the filesystem encoding and error handler.
-
PyObject *PyErr_SetFromWindowsErr(int ierr)¶
- 回傳值:總是為 NULL。 為 穩定 ABI 的一部分 on Windows 自 3.7 版本開始.
This is a convenience function to raise
OSError. If called with ierr of0, the error code returned by a call toGetLastError()is used instead. It calls the Win32 functionFormatMessage()to retrieve the Windows description of error code given by ierr orGetLastError(), then it constructs aOSErrorobject with thewinerrorattribute set to the error code, thestrerrorattribute set to the corresponding error message (gotten fromFormatMessage()), and then callsPyErr_SetObject(PyExc_OSError, object). This function always returnsNULL.可用性: Windows.
-
PyObject *PyErr_SetExcFromWindowsErr(PyObject *type, int ierr)¶
- 回傳值:總是為 NULL。 為 穩定 ABI 的一部分 on Windows 自 3.7 版本開始.
Similar to
PyErr_SetFromWindowsErr(), with an additional parameter specifying the exception type to be raised.可用性: Windows.
-
PyObject *PyErr_SetFromWindowsErrWithFilename(int ierr, const char *filename)¶
- 回傳值:總是為 NULL。 為 穩定 ABI 的一部分 on Windows 自 3.7 版本開始.
Similar to
PyErr_SetFromWindowsErr(), with the additional behavior that if filename is notNULL, it is decoded from the filesystem encoding (os.fsdecode()) and passed to the constructor ofOSErroras a third parameter to be used to define thefilenameattribute of the exception instance.可用性: Windows.
-
PyObject *PyErr_SetExcFromWindowsErrWithFilenameObject(PyObject *type, int ierr, PyObject *filename)¶
- 回傳值:總是為 NULL。 為 穩定 ABI 的一部分 on Windows 自 3.7 版本開始.
Similar to
PyErr_SetExcFromWindowsErr(), with the additional behavior that if filename is notNULL, it is passed to the constructor ofOSErroras a third parameter to be used to define thefilenameattribute of the exception instance.可用性: Windows.
-
PyObject *PyErr_SetExcFromWindowsErrWithFilenameObjects(PyObject *type, int ierr, PyObject *filename, PyObject *filename2)¶
- 回傳值:總是為 NULL。 為 穩定 ABI 的一部分 on Windows 自 3.7 版本開始.
Similar to
PyErr_SetExcFromWindowsErrWithFilenameObject(), but accepts a second filename object.可用性: Windows.
在 3.4 版被加入.
-
PyObject *PyErr_SetExcFromWindowsErrWithFilename(PyObject *type, int ierr, const char *filename)¶
- 回傳值:總是為 NULL。 為 穩定 ABI 的一部分 on Windows 自 3.7 版本開始.
Similar to
PyErr_SetFromWindowsErrWithFilename(), with an additional parameter specifying the exception type to be raised.可用性: Windows.
-
PyObject *PyErr_SetImportError(PyObject *msg, PyObject *name, PyObject *path)¶
- 回傳值:總是為 NULL。 為 穩定 ABI 的一部分 自 3.7 版本開始.
This is a convenience function to raise
ImportError. msg will be set as the exception's message string. name and path, both of which can beNULL, will be set as theImportError's respectivenameandpathattributes.在 3.3 版被加入.
-
PyObject *PyErr_SetImportErrorSubclass(PyObject *exception, PyObject *msg, PyObject *name, PyObject *path)¶
- 回傳值:總是為 NULL。 為 穩定 ABI 的一部分 自 3.6 版本開始.
Much like
PyErr_SetImportError()but this function allows for specifying a subclass ofImportErrorto raise.在 3.6 版被加入.
-
void PyErr_SyntaxLocationObject(PyObject *filename, int lineno, int col_offset)¶
Set file, line, and offset information for the current exception. If the current exception is not a
SyntaxError, then it sets additional attributes, which make the exception printing subsystem think the exception is aSyntaxError.在 3.4 版被加入.
-
void PyErr_RangedSyntaxLocationObject(PyObject *filename, int lineno, int col_offset, int end_lineno, int end_col_offset)¶
Similar to
PyErr_SyntaxLocationObject(), but also sets the end_lineno and end_col_offset information for the current exception.在 3.10 版被加入.
-
void PyErr_SyntaxLocationEx(const char *filename, int lineno, int col_offset)¶
- 為 穩定 ABI 的一部分 自 3.7 版本開始.
Like
PyErr_SyntaxLocationObject(), but filename is a byte string decoded from the filesystem encoding and error handler.在 3.2 版被加入.
-
void PyErr_SyntaxLocation(const char *filename, int lineno)¶
- 為 穩定 ABI 的一部分.
Like
PyErr_SyntaxLocationEx(), but the col_offset parameter is omitted.
-
void PyErr_BadInternalCall()¶
- 為 穩定 ABI 的一部分.
This is a shorthand for
PyErr_SetString(PyExc_SystemError, message), where message indicates that an internal operation (e.g. a Python/C API function) was invoked with an illegal argument. It is mostly for internal use.
-
PyObject *PyErr_ProgramTextObject(PyObject *filename, int lineno)¶
Get the source line in filename at line lineno. filename should be a Python
strobject.On success, this function returns a Python string object with the found line. On failure, this function returns
NULLwithout an exception set.
-
PyObject *PyErr_ProgramText(const char *filename, int lineno)¶
- 為 穩定 ABI 的一部分.
Similar to
PyErr_ProgramTextObject(), but filename is a const char*, which is decoded with the filesystem encoding and error handler, instead of a Python object reference.
發出警告¶
Use these functions to issue warnings from C code. They mirror similar
functions exported by the Python warnings module. They normally
print a warning message to sys.stderr; however, it is
also possible that the user has specified that warnings are to be turned into
errors, and in that case they will raise an exception. It is also possible that
the functions raise an exception because of a problem with the warning machinery.
The return value is 0 if no exception is raised, or -1 if an exception
is raised. (It is not possible to determine whether a warning message is
actually printed, nor what the reason is for the exception; this is
intentional.) If an exception is raised, the caller should do its normal
exception handling (for example, Py_DECREF() owned references and return
an error value).
-
int PyErr_WarnEx(PyObject *category, const char *message, Py_ssize_t stack_level)¶
- 為 穩定 ABI 的一部分.
Issue a warning message. The category argument is a warning category (see below) or
NULL; the message argument is a UTF-8 encoded string. stack_level is a positive number giving a number of stack frames; the warning will be issued from the currently executing line of code in that stack frame. A stack_level of 1 is the function callingPyErr_WarnEx(), 2 is the function above that, and so forth.Warning categories must be subclasses of
PyExc_Warning;PyExc_Warningis a subclass ofPyExc_Exception; the default warning category isPyExc_RuntimeWarning. The standard Python warning categories are available as global variables whose names are enumerated at 警告型別.For information about warning control, see the documentation for the
warningsmodule and the-Woption in the command line documentation. There is no C API for warning control.
-
int PyErr_WarnExplicitObject(PyObject *category, PyObject *message, PyObject *filename, int lineno, PyObject *module, PyObject *registry)¶
Issue a warning message with explicit control over all warning attributes. This is a straightforward wrapper around the Python function
warnings.warn_explicit(); see there for more information. The module and registry arguments may be set toNULLto get the default effect described there.在 3.4 版被加入.
- int PyErr_WarnExplicit(PyObject *category, const char *message, const char *filename, int lineno, const char *