Penanganan Pengecualian¶
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).
Зокрема, індикатор помилки складається з трьох покажчиків на об’єкти: тип винятку, значення винятку та об’єкт трасування. Будь-який із цих покажчиків може бути NULL
, якщо не встановлено (хоча деякі комбінації заборонені, наприклад, ви не можете мати не NULL
трасування, якщо тип винятку NULL
).
Gdy zadanie musi zawieźć z powodu błędu zadania które wywołało, ogólnie nie ustawia ona wskaźnika błędu; podzadanie które zostało wywołane już go ustawiła. Jest on odpowiedzialny albo za obsługę błędu i wyczyszczenie wskaźnika sytuacji wyjątkowej lub powrót po sprzątnięciu jakichkolwiek zasobów które utrzymuje (takich jak odwołania do przedmiotów lub zajęte pamięci); nie powinien kontynuować zwyczajnie jeśli nie jest przygotowany do obsługi błędu. Jeśli kończy z powodu błędu, istotne jest zwrócenie uwagi wołającego że został zgłoszony błąd. Jeśli błąd nie jest obsługiwany lub propagowany właściwie, dodatkowe odwołania do sprzęgu języka pytonowskiego/C mogą nie zachowywać się tak, jak planowano i mogą zawieźć w nieoczekiwane sposoby.
Catatan
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).
Mencetak dan membersihkan¶
-
void PyErr_Clear()¶
- Part of the Stable ABI.
Очистіть індикатор помилки. Якщо індикатор помилки не встановлено, ефекту немає.
-
void PyErr_PrintEx(int set_sys_last_vars)¶
- Part of the Stable ABI.
Надрукуйте стандартне відстеження до
sys.stderr
і очистіть індикатор помилки. Якщо помилка не єSystemExit
, у такому випадку трасування не друкується, і процес Python завершить роботу з кодом помилки, указаним екземпляромSystemExit
.Викликайте цю функцію лише, коли встановлено індикатор помилки. Інакше це призведе до фатальної помилки!
If set_sys_last_vars is nonzero, the variable
sys.last_exc
is set to the printed exception. For backwards compatibility, the deprecated variablessys.last_type
,sys.last_value
andsys.last_traceback
are also set to the type, value and traceback of this exception, respectively.Berubah pada versi 3.12: The setting of
sys.last_exc
was added.
-
void PyErr_Print()¶
- Part of the Stable ABI.
Alias dari
PyErr_PrintEx(1)
.
-
void PyErr_WriteUnraisable(PyObject *obj)¶
- Part of the Stable ABI.
Викликайте
sys.unraisablehook()
, використовуючи поточний виняток і аргумент obj.This utility function prints a warning message to
sys.stderr
when 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.При виклику цієї функції необхідно встановити виняток.
Berubah pada versi 3.4: Print a traceback. Print only traceback if obj is
NULL
.Berubah pada versi 3.8: Use
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.Added in version 3.13.
-
void PyErr_DisplayException(PyObject *exc)¶
- Part of the Stable ABI since version 3.12.
Print the standard traceback display of
exc
tosys.stderr
, including chained exceptions and notes.Added in version 3.12.
Menghasilkan pengecualian¶
Ці функції допомагають встановити індикатор помилки поточного потоку. Для зручності деякі з цих функцій завжди повертатимуть покажчик NULL
для використання в операторі return
.
-
void PyErr_SetString(PyObject *type, const char *message)¶
- Part of the Stable 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)¶
- Part of the Stable ABI.
Ця функція схожа на
PyErr_SetString()
, але дозволяє вказати довільний об’єкт Python для "значення" винятку.
-
PyObject *PyErr_Format(PyObject *exception, const char *format, ...)¶
- Return value: Always NULL. Part of the Stable ABI.
Ця функція встановлює індикатор помилки та повертає
NULL
. exception має бути класом винятків Python. format і наступні параметри допомагають відформатувати повідомлення про помилку; вони мають те саме значення та значення, що й уPyUnicode_FromFormat()
. format — це рядок у кодуванні ASCII.
-
PyObject *PyErr_FormatV(PyObject *exception, const char *format, va_list vargs)¶
- Return value: Always NULL. Part of the Stable ABI since version 3.5.
Те саме, що
PyErr_Format()
, але приймає аргументva_list
, а не змінну кількість аргументів.Added in version 3.5.
-
void PyErr_SetNone(PyObject *type)¶
- Part of the Stable ABI.
Це скорочення для
PyErr_SetObject(type, Py_None)
.
-
int PyErr_BadArgument()¶
- Part of the Stable ABI.
Це скорочення для
PyErr_SetString(PyExc_TypeError, повідомлення)
, де повідомлення вказує на те, що вбудовану операцію було викликано з недопустимим аргументом. В основному він призначений для внутрішнього використання.
-
PyObject *PyErr_NoMemory()¶
- Return value: Always NULL. Part of the Stable ABI.
Це скорочення для
PyErr_SetNone(PyExc_MemoryError)
; він повертаєNULL
, тому функція розподілу об’єктів може написатиreturn PyErr_NoMemory();
, коли їй вичерпується пам’ять.
-
PyObject *PyErr_SetFromErrno(PyObject *type)¶
- Return value: Always NULL. Part of the Stable 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 integererrno
value and whose second item is the corresponding error message (gotten fromstrerror()
), and then callsPyErr_SetObject(type, object)
. On Unix, when theerrno
value 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)¶
- Return value: Always NULL. Part of the Stable 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 ofOSError
exception, this is used to define thefilename
attribute of the exception instance.
-
PyObject *PyErr_SetFromErrnoWithFilenameObjects(PyObject *type, PyObject *filenameObject, PyObject *filenameObject2)¶
- Return value: Always NULL. Part of the Stable ABI since version 3.7.
Подібно до
PyErr_SetFromErrnoWithFilenameObject()
, але приймає другий об’єкт імені файлу, щоб викликати помилки, коли функція, яка приймає два імені файлу, виходить з ладу.Added in version 3.4.
-
PyObject *PyErr_SetFromErrnoWithFilename(PyObject *type, const char *filename)¶
- Return value: Always NULL. Part of the Stable 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)¶
- Return value: Always NULL. Part of the Stable ABI on Windows since version 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 aOSError
object with thewinerror
attribute set to the error code, thestrerror
attribute set to the corresponding error message (gotten fromFormatMessage()
), and then callsPyErr_SetObject(PyExc_OSError, object)
. This function always returnsNULL
.Availability: Windows.
-
PyObject *PyErr_SetExcFromWindowsErr(PyObject *type, int ierr)¶
- Return value: Always NULL. Part of the Stable ABI on Windows since version 3.7.
Подібно до
PyErr_SetFromWindowsErr()
, з додатковим параметром, що визначає тип винятку, який буде створено.Availability: Windows.
-
PyObject *PyErr_SetFromWindowsErrWithFilename(int ierr, const char *filename)¶
- Return value: Always NULL. Part of the Stable ABI on Windows since version 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 ofOSError
as a third parameter to be used to define thefilename
attribute of the exception instance.Availability: Windows.
-
PyObject *PyErr_SetExcFromWindowsErrWithFilenameObject(PyObject *type, int ierr, PyObject *filename)¶
- Return value: Always NULL. Part of the Stable ABI on Windows since version 3.7.
Similar to
PyErr_SetExcFromWindowsErr()
, with the additional behavior that if filename is notNULL
, it is passed to the constructor ofOSError
as a third parameter to be used to define thefilename
attribute of the exception instance.Availability: Windows.
-
PyObject *PyErr_SetExcFromWindowsErrWithFilenameObjects(PyObject *type, int ierr, PyObject *filename, PyObject *filename2)¶
- Return value: Always NULL. Part of the Stable ABI on Windows since version 3.7.
Подібно до
PyErr_SetExcFromWindowsErrWithFilenameObject()
, але приймає другий об’єкт імені файлу.Availability: Windows.
Added in version 3.4.
-
PyObject *PyErr_SetExcFromWindowsErrWithFilename(PyObject *type, int ierr, const char *filename)¶
- Return value: Always NULL. Part of the Stable ABI on Windows since version 3.7.
Подібно до
PyErr_SetFromWindowsErrWithFilename()
, з додатковим параметром, що визначає тип винятку, який буде створено.Availability: Windows.
-
PyObject *PyErr_SetImportError(PyObject *msg, PyObject *name, PyObject *path)¶
- Return value: Always NULL. Part of the Stable ABI since version 3.7.
Це зручна функція для виклику
ImportError
. msg буде встановлено як рядок повідомлення винятку. name і path, обидва з яких можуть мати значенняNULL
, буде встановлено як відповідні атрибутиname
іpath
ImportError
.Added in version 3.3.
-
PyObject *PyErr_SetImportErrorSubclass(PyObject *exception, PyObject *msg, PyObject *name, PyObject *path)¶
- Return value: Always NULL. Part of the Stable ABI since version 3.6.
Дуже схоже на
PyErr_SetImportError()
, але ця функція дозволяє вказати підкласImportError
для підвищення.Added in version 3.6.
-
void PyErr_SyntaxLocationObject(PyObject *filename, int lineno, int col_offset)¶
Установіть інформацію про файл, рядок і зсув для поточного винятку. Якщо поточний виняток не є
SyntaxError
, тоді він встановлює додаткові атрибути, які змушують підсистему друку виключення вважати, що виняток єSyntaxError
.Added in version 3.4.
-
void PyErr_SyntaxLocationEx(const char *filename, int lineno, int col_offset)¶
- Part of the Stable ABI since version 3.7.
Like
PyErr_SyntaxLocationObject()
, but filename is a byte string decoded from the filesystem encoding and error handler.Added in version 3.2.
-
void PyErr_SyntaxLocation(const char *filename, int lineno)¶
- Part of the Stable ABI.
Як
PyErr_SyntaxLocationEx()
, але параметр col_offset опущено.
-
void PyErr_BadInternalCall()¶
- Part of the Stable ABI.
Це скорочення для
PyErr_SetString(PyExc_SystemError, повідомлення)
, де повідомлення вказує на те, що внутрішня операція (наприклад, функція Python/C API) була викликана з недопустимим аргументом. В основному він призначений для внутрішнього використання.
Menerbitkan peringatan¶
Використовуйте ці функції, щоб видавати попередження з коду C. Вони відображають аналогічні функції, експортовані модулем Python warnings
. Зазвичай вони друкують попередження на sys.stderr; однак також можливо, що користувач вказав, що попередження потрібно перетворити на помилки, і в такому випадку вони викличуть виняток. Також можливо, що функції викликають виняток через проблему з механізмом попередження. Повертається значення 0
, якщо не викликається виняткова ситуація, або -1
, якщо виникає виняток. (Неможливо визначити, чи справді друкується попереджувальне повідомлення, а також причину винятку; це навмисно.) Якщо виникає виняток, абонент, що викликає, має виконати звичайну обробку винятків (наприклад, Py_DECREF()
належать посилання та повертають значення помилки).
-
int PyErr_WarnEx(PyObject *category, const char *message, Py_ssize_t stack_level)¶
- Part of the Stable ABI.
Видавати попереджувальне повідомлення. Аргумент category є категорією попередження (див. нижче) або
NULL
; аргумент message — це рядок у кодуванні UTF-8. stack_level — додатне число, яке дає кількість кадрів стека; попередження буде видано з поточного рядка коду в цьому фреймі стека. Stack_level 1 — це функція, яка викликаєPyErr_WarnEx()
, 2 — це функція, яка стоїть вище, і так далі.Категорії попереджень мають бути підкласами
PyExc_Warning
;PyExc_Warning
є підкласомPyExc_Exception
; стандартна категорія попередження:PyExc_RuntimeWarning
. Стандартні категорії попереджень Python доступні як глобальні змінні, імена яких пронумеровані в Warning types.Щоб отримати інформацію про керування попередженнями, перегляньте документацію до модуля
warnings
і опції-W
у документації командного рядка. Немає C API для керування попередженнями.
-
int PyErr_WarnExplicitObject(PyObject *category, PyObject *message, PyObject *filename, int lineno, PyObject *module, PyObject *registry)¶
Видавати попереджувальне повідомлення з явним керуванням усіма атрибутами попередження. Це проста обгортка функції Python
warnings.warn_explicit()
; дивіться там для отримання додаткової інформації. Для аргументів module і registry можна встановити значенняNULL
, щоб отримати описаний там ефект за замовчуванням.Added in version 3.4.
-
int PyErr_WarnExplicit(PyObject *category, const char *message, const char *filename, int lineno, const char *module, PyObject *registry)¶
- Part of the Stable ABI.
Similar to
PyErr_WarnExplicitObject()
except that message and module are UTF-8 encoded strings, and filename is decoded from the filesystem encoding and error handler.
-
int PyErr_WarnFormat(PyObject *category, Py_ssize_t stack_level, const char *format, ...)¶
- Part of the Stable ABI.
Функція схожа на
PyErr_WarnEx()
, але використовуйтеPyUnicode_FromFormat()
для форматування повідомлення попередження. format — це рядок у кодуванні ASCII.Added in version 3.2.
-
int PyErr_ResourceWarning(PyObject *source, Py_ssize_t stack_level, const char *format, ...)¶
- Part of the Stable ABI since version 3.6.
Function similar to
PyErr_WarnFormat()
, but category isResourceWarning
and it passes source towarnings.WarningMessage
.Added in version 3.6.
Meminta indikator kesalahan¶
-
PyObject *PyErr_Occurred()¶
- Return value: Borrowed reference. Part of the Stable ABI.
Test whether the error indicator is set. If set, return the exception type (the first argument to the last call to one of the
PyErr_Set*
functions or toPyErr_Restore()
). If not set, returnNULL
. You do not own a reference to the return value, so you do not need toPy_DECREF()
it.The caller must hold the GIL.
Catatan
Не порівнюйте повернуте значення з певним винятком; замість цього використовуйте
PyErr_ExceptionMatches()
, як показано нижче. (Порівняння може бути легко невдалим, оскільки виняток може бути екземпляром замість класу, у випадку винятку класу, або він може бути підкласом очікуваного винятку.)
-
int PyErr_ExceptionMatches(PyObject *exc)¶
- Part of the Stable ABI.
Еквівалент
PyErr_GivenExceptionMatches(PyErr_Occurred(), exc)
. Це слід викликати лише тоді, коли фактично встановлено виняток; порушення доступу до пам'яті відбудеться, якщо не було викликано жодного винятку.
-
int PyErr_GivenExceptionMatches(PyObject *given, PyObject *exc)¶
- Part of the Stable ABI.
Повертає true, якщо given виняток відповідає типу винятку в exc. Якщо exc є об’єктом класу, це також повертає true, коли given є екземпляром підкласу. Якщо exc є кортежем, усі типи винятків у кортежі (і рекурсивно в підкортежах) шукаються на відповідність.
-
PyObject *PyErr_GetRaisedException(void)¶
- Return value: New reference. Part of the Stable ABI since version 3.12.
Return the exception currently being raised, clearing the error indicator at the same time. Return
NULL
if the error indicator is not set.This function is used by code that needs to catch exceptions, or code that needs to save and restore the error indicator temporarily.
Sebagai contoh:
{ PyObject *exc = PyErr_GetRaisedException(); /* ... code that might produce other errors ... */ PyErr_SetRaisedException(exc); }
Lihat juga
PyErr_GetHandledException()
, to save the exception currently being handled.Added in version 3.12.
-
void PyErr_SetRaisedException(PyObject *exc)¶
- Part of the Stable ABI since version 3.12.
Set exc as the exception currently being raised, clearing the existing exception if one is set.
Peringatan
This call steals a reference to exc, which must be a valid exception.
Added in version 3.12.
-
void PyErr_Fetch(PyObject **ptype, PyObject **pvalue, PyObject **ptraceback)¶
- Part of the Stable ABI.
Ditinggalkan sejak versi 3.12: Use
PyErr_GetRaisedException()
instead.Отримати індикатор помилки в трьох змінних, адреси яких передано. Якщо індикатор помилки не встановлено, установіть для всіх трьох змінних значення
NULL
. Якщо його встановлено, його буде очищено, і ви матимете посилання на кожен отриманий об’єкт. Значення та об’єкт трасування можуть бутиNULL
, навіть якщо об’єкт типу не є таким.Catatan
This function is normally only used by legacy code that needs to catch exceptions or save and restore the error indicator temporarily.
Sebagai contoh:
{ PyObject *type, *value, *traceback; PyErr_Fetch(&type, &value, &traceback); /* ... code that might produce other errors ... */ PyErr_Restore(type, value, traceback); }
-
void PyErr_Restore(PyObject *type, PyObject *value, PyObject *traceback)¶
- Part of the Stable ABI.
Ditinggalkan sejak versi 3.12: Use
PyErr_SetRaisedException()
instead.Set the error indicator from the three objects, type, value, and traceback, clearing the existing exception if one is set. If the objects are
NULL
, the error indicator is cleared. Do not pass aNULL
type and non-NULL
value or traceback. The exception type should be a class. Do not pass an invalid exception type or value. (Violating these rules will cause subtle problems later.) This call takes away a reference to each object: you must own a reference to each object before the call and after the call you no longer own these references. (If you don't understand this, don't use this function. I warned you.)Catatan
This function is normally only used by legacy code that needs to save and restore the error indicator temporarily. Use
PyErr_Fetch()
to save the current error indicator.
-
void PyErr_NormalizeException(PyObject **exc, PyObject **val, PyObject **tb)¶
- Part of the Stable ABI.
Ditinggalkan sejak versi 3.12: Use
PyErr_GetRaisedException()
instead, to avoid any possible de-normalization.За певних обставин значення, які повертає
PyErr_Fetch()
нижче, можуть бути "ненормалізованими", тобто*exc
є об’єктом класу, але*val
не є екземпляром того самого класу . У цьому випадку цю функцію можна використовувати для створення екземпляра класу. Якщо значення вже нормалізовані, нічого не відбувається. Відкладену нормалізацію реалізовано для покращення продуктивності.Catatan
This function does not implicitly set the
__traceback__
attribute on the exception value. If setting the traceback appropriately is desired, the following additional snippet is needed:if (tb != NULL) { PyException_SetTraceback(val, tb); }
-
PyObject *PyErr_GetHandledException(void)¶
- Part of the Stable ABI since version 3.11.
Retrieve the active exception instance, as would be returned by
sys.exception()
. This refers to an exception that was already caught, not to an exception that was freshly raised. Returns a new reference to the exception orNULL
. Does not modify the interpreter's exception state.Catatan
This function is not normally used by code that wants to handle exceptions. Rather, it can be used when code needs to save and restore the exception state temporarily. Use
PyErr_SetHandledException()
to restore or clear the exception state.Added in version 3.11.
-
void PyErr_SetHandledException(PyObject *exc)¶
- Part of the Stable ABI since version 3.11.
Set the active exception, as known from
sys.exception()
. This refers to an exception that was already caught, not to an exception that was freshly raised. To clear the exception state, passNULL
.Catatan
This function is not normally used by code that wants to handle exceptions. Rather, it can be used when code needs to save and restore the exception state temporarily. Use
PyErr_GetHandledException()
to get the exception state.Added in version 3.11.
-
void PyErr_GetExcInfo(PyObject **ptype, PyObject **pvalue, PyObject **ptraceback)¶
- Part of the Stable ABI since version 3.7.
Retrieve the old-style representation of the exception info, as known from
sys.exc_info()
. This refers to an exception that was already caught, not to an exception that was freshly raised. Returns new references for the three objects, any of which may beNULL
. Does not modify the exception info state. This function is kept for backwards compatibility. Prefer usingPyErr_GetHandledException()
.Catatan
Ця функція зазвичай не використовується кодом, який хоче обробляти винятки. Натомість його можна використовувати, коли коду потрібно тимчасово зберегти та відновити винятковий стан. Використовуйте
PyErr_SetExcInfo()
, щоб відновити або видалити винятковий стан.Added in version 3.3.
-
void PyErr_SetExcInfo(PyObject *type, PyObject *value, PyObject *traceback)¶
- Part of the Stable ABI since version 3.7.
Set the exception info, as known from
sys.exc_info()
. This refers to an exception that was already caught, not to an exception that was freshly raised. This function steals the references of the arguments. To clear the exception state, passNULL
for all three arguments. This function is kept for backwards compatibility. Prefer usingPyErr_SetHandledException()
.Catatan
Ця функція зазвичай не використовується кодом, який хоче обробляти винятки. Натомість його можна використовувати, коли коду потрібно тимчасово зберегти та відновити винятковий стан. Використовуйте
PyErr_GetExcInfo()
, щоб прочитати винятковий стан.Added in version 3.3.
Berubah pada versi 3.11: The
type
andtraceback
arguments are no longer used and can be NULL. The interpreter now derives them from the exception instance (thevalue
argument). The function still steals references of all three arguments.
Penanganan Sinyal Signal¶
-
int PyErr_CheckSignals()¶
- Part of the Stable ABI.
This function interacts with Python's signal handling.
If the function is called from the main thread and under the main Python interpreter, it checks whether a signal has been sent to the processes and if so, invokes the corresponding signal handler. If the
signal
module is supported, this can invoke a signal handler written in Python.The function attempts to handle all pending signals, and then returns
0
. However, if a Python signal handler raises an exception, the error indicator is set and the function returns-1
immediately (such that other pending signals may not have been handled yet: they will be on the nextPyErr_CheckSignals()
invocation).If the function is called from a non-main thread, or under a non-main Python interpreter, it does nothing and returns
0
.This function can be called by long-running C code that wants to be interruptible by user requests (such as by pressing Ctrl-C).
Catatan
The default Python signal handler for
SIGINT
raises theKeyboardInterrupt
exception.
-
void PyErr_SetInterrupt()¶
- Part of the Stable ABI.
Simulate the effect of a
SIGINT
signal arriving. This is equivalent toPyErr_SetInterruptEx(SIGINT)
.Catatan
This function is async-signal-safe. It can be called without the GIL and from a C signal handler.
-
int PyErr_SetInterruptEx(int signum)¶
- Part of the Stable ABI since version 3.10.
Simulate the effect of a signal arriving. The next time
PyErr_CheckSignals()
is called, the Python signal handler for the given signal number will be called.This function can be called by C code that sets up its own signal handling and wants Python signal handlers to be invoked as expected when an interruption is requested (for example when the user presses Ctrl-C to interrupt an operation).
If the given signal isn't handled by Python (it was set to
signal.SIG_DFL
orsignal.SIG_IGN
), it will be ignored.If signum is outside of the allowed range of signal numbers,
-1
is returned. Otherwise,0
is returned. The error indicator is never changed by this function.Catatan
This function is async-signal-safe. It can be called without the GIL and from a C signal handler.
Added in version 3.10.
-
int PySignal_SetWakeupFd(int fd)¶
Ця допоміжна функція вказує дескриптор файлу, до якого номер сигналу записується як один байт кожного разу, коли надходить сигнал. fd має бути неблокуючим. Він повертає попередній такий файловий дескриптор.
Значення
-1
вимикає функцію; це початковий стан. Це еквівалентноsignal.set_wakeup_fd()
у Python, але без перевірки помилок. fd має бути дійсним дескриптором файлу. Функцію слід викликати лише з основного потоку.Berubah pada versi 3.5: У Windows функція тепер також підтримує ручки сокетів.
Kelas Pengecualian¶
-
PyObject *PyErr_NewException(const char *name, PyObject *base, PyObject *dict)¶
- Return value: New reference. Part of the Stable ABI.
Ця службова функція створює та повертає новий клас винятків. Аргумент name має бути назвою нового винятку, рядком C у формі
module.classname
. Аргументи base і dict зазвичай мають значенняNULL
. Це створює об’єкт класу, похідний відException
(доступний у C якPyExc_Exception
).The
__module__
attribute of the new class is set to the first part (up to the last dot) of the name argument, and the class name is set to the last part (after the last dot). The base argument can be used to specify alternate base classes; it can either be only one class or a tuple of classes. The dict argument can be used to specify a dictionary of class variables and methods.
-
PyObject *PyErr_NewExceptionWithDoc(const char *name, const char *doc, PyObject *base, PyObject *dict)¶
- Return value: New reference. Part of the Stable ABI.
Те саме, що
PyErr_NewException()
, за винятком того, що новому класу винятків можна легко надати рядок документації: якщо doc не єNULL
, він використовуватиметься як рядок документації для класу винятків.Added in version 3.2.
-
int PyExceptionClass_Check(PyObject *ob)¶
Return non-zero if ob is an exception class, zero otherwise. This function always succeeds.
-
const char *PyExceptionClass_Name(PyObject *ob)¶
- Part of the Stable ABI since version 3.8.
Return
tp_name
of the exception class ob.
Objek Pengecualian¶
-
PyObject *PyException_GetTraceback(PyObject *ex)¶
- Return value: New reference. Part of the Stable ABI.
Return the traceback associated with the exception as a new reference, as accessible from Python through the
__traceback__
attribute. If there is no traceback associated, this returnsNULL
.
-
int PyException_SetTraceback(PyObject *ex, PyObject *tb)¶
- Part of the Stable ABI.
Установіть для трасування, пов’язаного з винятком, значення tb. Використовуйте
Py_None
, щоб очистити його.
-
PyObject *PyException_GetContext(PyObject *ex)¶
- Return value: New reference. Part of the Stable ABI.
Return the context (another exception instance during whose handling ex was raised) associated with the exception as a new reference, as accessible from Python through the
__context__
attribute. If there is no context associated, this returnsNULL
.
-
void PyException_SetContext(PyObject *ex, PyObject *ctx)¶
- Part of the Stable ABI.
Установіть для контексту, пов’язаного з винятком, значення ctx. Щоб очистити його, використовуйте
NULL
. Немає перевірки типу, щоб переконатися, що ctx є винятком. Це краде посилання на ctx.
-
PyObject *PyException_GetCause(PyObject *ex)¶
- Return value: New reference. Part of the Stable ABI.
Return the cause (either an exception instance, or
None
, set byraise ... from ...
) associated with the exception as a new reference, as accessible from Python through the__cause__
attribute.
-
void PyException_SetCause(PyObject *ex, PyObject *cause)¶
- Part of the Stable ABI.
Set the cause associated with the exception to cause. Use
NULL
to clear it. There is no type check to make sure that cause is either an exception instance orNone
. This steals a reference to cause.The
__suppress_context__
attribute is implicitly set toTrue
by this function.
-
PyObject *PyException_GetArgs(PyObject *ex)¶
- Return value: New reference. Part of the Stable ABI since version 3.12.
Return
args
of exception ex.
-
void PyException_SetArgs(PyObject *ex, PyObject *args)¶
- Part of the Stable ABI since version 3.12.
Set
args
of exception ex to args.
-
PyObject *PyUnstable_Exc_PrepReraiseStar(PyObject *orig, PyObject *excs)¶
- This is Unstable API. It may change without warning in minor releases.
Implement part of the interpreter's implementation of
except*
. orig is the original exception that was caught, and excs is the list of the exceptions that need to be raised. This list contains the unhandled part of orig, if any, as well as the exceptions that were raised from theexcept*
clauses (so they have a different traceback from orig) and those that were reraised (and have the same traceback as orig). Return theExceptionGroup
that needs to be reraised in the end, orNone
if there is nothing to reraise.Added in version 3.12.
Objek Pengecualian Unicode¶
Наступні функції використовуються для створення та зміни винятків Unicode з C.
-
PyObject *PyUnicodeDecodeError_Create(const char *encoding, const char *object, Py_ssize_t length, Py_ssize_t start, Py_ssize_t end, const char *reason)¶
- Return value: New reference. Part of the Stable ABI.
Створіть об’єкт
UnicodeDecodeError
з атрибутами encoding, object, length, start, end і reason. encoding і reason є рядками в кодуванні UTF-8.
-
PyObject *PyUnicodeDecodeError_GetEncoding(PyObject *exc)¶
-
PyObject *PyUnicodeEncodeError_GetEncoding(PyObject *exc)¶
- Return value: New reference. Part of the Stable ABI.
Повертає атрибут encoding даного об’єкта винятку.
-
PyObject *PyUnicodeDecodeError_GetObject(PyObject *exc)¶
-
PyObject *PyUnicodeEncodeError_GetObject(PyObject *exc)¶
-
PyObject *PyUnicodeTranslateError_GetObject(PyObject *exc)¶
- Return value: New reference. Part of the Stable ABI.
Повертає атрибут object даного об’єкта винятку.
-
int PyUnicodeDecodeError_GetStart(PyObject *exc, Py_ssize_t *start)¶
-
int PyUnicodeEncodeError_GetStart(PyObject *exc, Py_ssize_t *start)¶
-
int PyUnicodeTranslateError_GetStart(PyObject *exc, Py_ssize_t *start)¶
- Part of the Stable ABI.
Отримайте атрибут start даного об’єкта винятку та помістіть його в *start. початок не має бути
NULL
. Повертає0
в разі успіху,-1
у випадку невдачі.
-
int PyUnicodeDecodeError_SetStart(PyObject *exc, Py_ssize_t start)¶
-
int PyUnicodeEncodeError_SetStart(PyObject *exc, Py_ssize_t start)¶
-
int PyUnicodeTranslateError_SetStart(PyObject *exc, Py_ssize_t start)¶
- Part of the Stable ABI.
Set the start attribute of the given exception object to start. Return
0
on success,-1
on failure.
-
int PyUnicodeDecodeError_GetEnd(PyObject *exc, Py_ssize_t *end)¶
-
int PyUnicodeEncodeError_GetEnd(PyObject *exc, Py_ssize_t *end)¶
-
int PyUnicodeTranslateError_GetEnd(PyObject *exc, Py_ssize_t *end)¶
- Part of the Stable ABI.
Отримайте атрибут end даного об’єкта винятку та помістіть його в *end. end не має бути
NULL
. Повертає0
в разі успіху,-1
у випадку невдачі.
-
int PyUnicodeDecodeError_SetEnd(PyObject *exc, Py_ssize_t end)¶
-
int PyUnicodeEncodeError_SetEnd(PyObject *exc, Py_ssize_t end)¶
-
int PyUnicodeTranslateError_SetEnd(PyObject *exc, Py_ssize_t end)¶
- Part of the Stable ABI.
Установіть для атрибута end даного об’єкта винятку значення end. Повертає
0
в разі успіху,-1
у випадку невдачі.
-
PyObject *PyUnicodeDecodeError_GetReason(PyObject *exc)¶
-
PyObject *PyUnicodeEncodeError_GetReason(PyObject *exc)¶
-
PyObject *PyUnicodeTranslateError_GetReason(PyObject *exc)¶
- Return value: New reference. Part of the Stable ABI.
Повертає атрибут reason даного об’єкта винятку.
-
int PyUnicodeDecodeError_SetReason(PyObject *exc, const char *reason)¶
-
int PyUnicodeEncodeError_SetReason(PyObject *exc, const char *reason)¶
-
int PyUnicodeTranslateError_SetReason(PyObject *exc, const char *reason)¶
- Part of the Stable ABI.
Установіть для атрибута reason даного об’єкта винятку значення reason. Повертає
0
в разі успіху,-1
у випадку невдачі.
Kontrol Rekursi¶
Ці дві функції забезпечують спосіб виконання безпечних рекурсивних викликів на рівні C, як в ядрі, так і в модулях розширення. Вони потрібні, якщо рекурсивний код не обов’язково викликає код Python (який автоматично відстежує глибину рекурсії). Вони також не потрібні для реалізації tp_call, оскільки протокол виклику піклується про обробку рекурсії.
-
int Py_EnterRecursiveCall(const char *where)¶
- Part of the Stable ABI since version 3.9.
Позначає точку, де має бути виконано рекурсивний виклик C-рівня.
If
USE_STACKCHECK
is defined, this function checks if the OS stack overflowed usingPyOS_CheckStack()
. If this is the case, it sets aMemoryError
and returns a nonzero value.The function then checks if the recursion limit is reached. If this is the case, a
RecursionError
is set and a nonzero value is returned. Otherwise, zero is returned.де має бути рядок у кодуванні UTF-8, такий як
" у перевірці екземпляра"
, який об’єднується з повідомленнямRecursionError
, спричиненим обмеженням глибини рекурсії.Berubah pada versi 3.9: This function is now also available in the limited API.
-
void Py_LeaveRecursiveCall(void)¶
- Part of the Stable ABI since version 3.9.
Завершує
Py_EnterRecursiveCall()
. Потрібно викликати один раз для кожного успішного викликуPy_EnterRecursiveCall()
.Berubah pada versi 3.9: This function is now also available in the limited API.
Правильна реалізація tp_repr
для типів контейнерів вимагає спеціальної обробки рекурсії. Окрім захисту стека, tp_repr
також має відстежувати об’єкти, щоб запобігти циклам. Наступні дві функції полегшують цю функцію. По суті, це C еквівалент reprlib.recursive_repr()
.
-
int Py_ReprEnter(PyObject *object)¶
- Part of the Stable ABI.
Викликається на початку реалізації
tp_repr
для виявлення циклів.Якщо об’єкт уже оброблено, функція повертає додатне ціле число. У цьому випадку реалізація
tp_repr
має повертати рядковий об’єкт, що вказує на цикл. Як приклад, об’єктиdict
повертають{...}
, а об’єктиlist
повертають[...]
.Функція поверне від’ємне ціле число, якщо досягнуто обмеження рекурсії. У цьому випадку реалізація
tp_repr
зазвичай повинна повертатиNULL
.В іншому випадку функція повертає нуль, і реалізація
tp_repr
може продовжуватися нормально.
-
void Py_ReprLeave(PyObject *object)¶
- Part of the Stable ABI.
Завершує
Py_ReprEnter()
. Потрібно викликати один раз для кожного викликуPy_ReprEnter()
, який повертає нуль.
Exception and warning types¶
All standard Python exceptions and warning categories are available as global
variables whose names are PyExc_
followed by the Python exception name.
These have the type PyObject*; they are all class objects.
For completeness, here are all the variables:
Exception types¶
C name |
Python name |
---|---|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
Added in version 3.3: PyExc_BlockingIOError
, PyExc_BrokenPipeError
, PyExc_ChildProcessError
, PyExc_ConnectionError
, PyExc_ConnectionAbortedError
, PyExc_ConnectionRefusedError
, PyExc_ConnectionResetError
, PyExc_FileExistsError
, PyExc_FileNotFoundError
, PyExc_InterruptedError
, PyExc_IsADirectoryError
, PyExc_NotADirectoryError
, PyExc_PermissionError
, PyExc_ProcessLookupError
dan PyExc_TimeoutError
diperkenalkan berikut PEP 3151.
Added in version 3.5: PyExc_StopAsyncIteration
dan PyExc_RecursionError
.
Added in version 3.6: PyExc_ModuleNotFoundError
.
Added in version 3.11: PyExc_BaseExceptionGroup
.
OSError aliases¶
The following are a compatibility aliases to PyExc_OSError
.
Berubah pada versi 3.3: Раніше ці псевдоніми були окремими типами винятків.
C name |
Python name |
Catatan |
---|---|---|
|
||
|
||
|
Catatan:
PyExc_WindowsError
is only defined on Windows; protect code that
uses this by testing that the preprocessor macro MS_WINDOWS
is defined.
Warning types¶
C name |
Python name |
---|---|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
Added in version 3.2: PyExc_ResourceWarning
.
Added in version 3.10: PyExc_EncodingWarning
.