Обробка винятків

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).

Коли функція повинна вийти з ладу через те, що якась викликана нею функція вийшла з ладу, вона зазвичай не встановлює індикатор помилки; викликана ним функція вже встановила його. Він відповідає або за обробку помилки та очищення виняткової ситуації, або за повернення після очищення будь-яких ресурсів, які він утримує (наприклад, посилання на об’єкти чи розподіл пам’яті); він не повинен продовжуватися нормально, якщо він не готовий обробити помилку. Якщо ви повертаєтеся через помилку, важливо вказати абоненту, що була встановлена помилка. Якщо помилку не обробляти або ретельно розповсюджувати, додаткові виклики API Python/C можуть не працювати належним чином і можуть виникати загадкові збої.

Примітка

Індикатор помилки не є результатом sys.exc_info(). Перший відповідає винятку, який ще не перехоплено (і, отже, все ще поширюється), а другий повертає виняток після того, як він перехоплений (і, отже, припинив поширення).

Друк та розчистка

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 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 was added.

void PyErr_Print()
Part of the Stable ABI.

Псевдонім для 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.

При виклику цієї функції необхідно встановити виняток.

Змінено в версії 3.4: Print a traceback. Print only traceback if obj is NULL.

Змінено в версії 3.8: Use sys.unraisablehook().

void PyErr_DisplayException(PyObject *exc)
Part of the Stable ABI since version 3.12.

Print the standard traceback display of exc to sys.stderr, including chained exceptions and notes.

Added in version 3.12.

Створення винятків

Ці функції допомагають встановити індикатор помилки поточного потоку. Для зручності деякі з цих функцій завжди повертатимуть покажчик 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. with Py_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 integer errno value and whose second item is the corresponding error message (gotten from strerror()), and then calls PyErr_SetObject(type, object). On Unix, when the errno value is EINTR, indicating an interrupted system call, this calls PyErr_CheckSignals(), and if that set the error indicator, leaves it set to that. The function always returns NULL, so a wrapper function around a system call can write return 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 not NULL, it is passed to the constructor of type as a third parameter. In the case of OSError exception, this is used to define the filename 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.

Подібно до PyErr_SetFromErrnoWithFilenameObject(), але ім’я файлу подається як рядок C. ім’я файлу розшифровується з 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 of 0, the error code returned by a call to GetLastError() is used instead. It calls the Win32 function FormatMessage() to retrieve the Windows description of error code given by ierr or GetLastError(), then it constructs a OSError object with the winerror attribute set to the error code, the strerror attribute set to the corresponding error message (gotten from FormatMessage()), and then calls PyErr_SetObject(PyExc_OSError, object). This function always returns NULL.

Наявність: 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(), з додатковим параметром, що визначає тип винятку, який буде створено.

Наявність: 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 not NULL, it is decoded from the filesystem encoding (os.fsdecode()) and passed to the constructor of OSError as a third parameter to be used to define the filename attribute of the exception instance.

Наявність: 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 not NULL, it is passed to the constructor of OSError as a third parameter to be used to define the filename attribute of the exception instance.

Наявність: 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(), але приймає другий об’єкт імені файлу.

Наявність: 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(), з додатковим параметром, що визначає тип винятку, який буде створено.

Наявність: 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.

Подібно до PyErr_SyntaxLocationObject(), але filename — це рядок байтів, декодований з 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) була викликана з недопустимим аргументом. В основному він призначений для внутрішнього використання.

Винесення попереджень

Використовуйте ці функції, щоб видавати попередження з коду 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 доступні як глобальні змінні, імена яких пронумеровані в Стандартні категорії попереджень.

Щоб отримати інформацію про керування попередженнями, перегляньте документацію до модуля 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.

Подібно до PyErr_WarnExplicitObject(), за винятком того, що message і module є рядками в кодуванні UTF-8, а filename декодується з 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 is ResourceWarning and it passes source to warnings.WarningMessage.

Added in version 3.6.

Запит індикатора помилки

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 to PyErr_Restore()). If not set, return NULL. You do not own a reference to the return value, so you do not need to Py_DECREF() it.

Абонент повинен тримати GIL.

Примітка

Не порівнюйте повернуте значення з певним винятком; замість цього використовуйте 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.

Наприклад:

{
   PyObject *exc = PyErr_GetRaisedException();

   /* ... code that might produce other errors ... */

   PyErr_SetRaisedException(exc);
}

Дивись також

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.

Попередження

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.

Застаріло починаючи з версії 3.12: Use PyErr_GetRaisedException() instead.

Отримати індикатор помилки в трьох змінних, адреси яких передано. Якщо індикатор помилки не встановлено, установіть для всіх трьох змінних значення NULL. Якщо його встановлено, його буде очищено, і ви матимете посилання на кожен отриманий об’єкт. Значення та об’єкт трасування можуть бути NULL, навіть якщо об’єкт типу не є таким.

Примітка

This function is normally only used by legacy code that needs to catch exceptions or save and restore the error indicator temporarily.

Наприклад:

{
   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.

Застаріло починаючи з версії 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 a NULL 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.)

Примітка

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.

Застаріло починаючи з версії 3.12: Use PyErr_GetRaisedException() instead, to avoid any possible de-normalization.

За певних обставин значення, які повертає PyErr_Fetch() нижче, можуть бути «ненормалізованими», тобто *exc є об’єктом класу, але *val не є екземпляром того самого класу . У цьому випадку цю функцію можна використовувати для створення екземпляра класу. Якщо значення вже нормалізовані, нічого не відбувається. Відкладену нормалізацію реалізовано для покращення продуктивності.

Примітка

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 or NULL. Does not modify the interpreter’s exception state.

Примітка

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, pass NULL.

Примітка

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 be NULL. Does not modify the exception info state. This function is kept for backwards compatibility. Prefer using PyErr_GetHandledException().

Примітка

Ця функція зазвичай не використовується кодом, який хоче обробляти винятки. Натомість його можна використовувати, коли коду потрібно тимчасово зберегти та відновити винятковий стан. Використовуйте 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, pass NULL for all three arguments. This function is kept for backwards compatibility. Prefer using PyErr_SetHandledException().

Примітка

Ця функція зазвичай не використовується кодом, який хоче обробляти винятки. Натомість його можна використовувати, коли коду потрібно тимчасово зберегти та відновити винятковий стан. Використовуйте PyErr_GetExcInfo(), щоб прочитати винятковий стан.

Added in version 3.3.

Змінено в версії 3.11: The type and traceback arguments are no longer used and can be NULL. The interpreter now derives them from the exception instance (the value argument). The function still steals references of all three arguments.

Обробка сигналів

int PyErr_CheckSignals()
Part of the Stable ABI.

Ця функція взаємодіє з обробкою сигналів Python.

Якщо функція викликається з головного потоку та під основним інтерпретатором Python, вона перевіряє, чи було надіслано сигнал до процесів, і якщо так, викликає відповідний обробник сигналу. Якщо модуль signal підтримується, це може викликати обробник сигналів, написаний на Python.

Функція намагається обробити всі незавершені сигнали, а потім повертає 0. Однак, якщо обробник сигналів Python викликає виняток, індикатор помилки встановлюється, і функція негайно повертає -1 (наприклад, інші сигнали, що очікують на розгляд, ще не були оброблені: вони будуть на наступному PyErr_CheckSignals() виклик).

Якщо функція викликається з неосновного потоку або під неосновним інтерпретатором Python, вона нічого не робить і повертає 0.

Ця функція може бути викликана довгостроковим кодом C, який хоче бути перерваним запитами користувача (наприклад, натисканням Ctrl-C).

Примітка

The default Python signal handler for SIGINT raises the KeyboardInterrupt exception.

void PyErr_SetInterrupt()
Part of the Stable ABI.

Simulate the effect of a SIGINT signal arriving. This is equivalent to PyErr_SetInterruptEx(SIGINT).

Примітка

Ця функція безпечна для асинхронного сигналу. Його можна викликати без GIL і з обробника сигналів C.

int PyErr_SetInterruptEx(int signum)
Part of the Stable ABI since version 3.10.

Імітація ефекту надходження сигналу. Під час наступного виклику PyErr_CheckSignals() буде викликано обробник сигналу Python для заданого номера сигналу.

Цю функцію можна викликати за допомогою коду C, який налаштовує власну обробку сигналів і хоче, щоб обробники сигналів Python викликалися належним чином, коли надходить запит на переривання (наприклад, коли користувач натискає Ctrl-C, щоб перервати операцію).

If the given signal isn’t handled by Python (it was set to signal.SIG_DFL or signal.SIG_IGN), it will be ignored.

Якщо signum знаходиться за межами дозволеного діапазону чисел сигналу, повертається -1. В іншому випадку повертається 0. Ця функція ніколи не змінює індикатор помилки.

Примітка

Ця функція безпечна для асинхронного сигналу. Його можна викликати без GIL і з обробника сигналів C.

Added in version 3.10.

int PySignal_SetWakeupFd(int fd)

Ця допоміжна функція вказує дескриптор файлу, до якого номер сигналу записується як один байт кожного разу, коли надходить сигнал. fd має бути неблокуючим. Він повертає попередній такий файловий дескриптор.

Значення -1 вимикає функцію; це початковий стан. Це еквівалентно signal.set_wakeup_fd() у Python, але без перевірки помилок. fd має бути дійсним дескриптором файлу. Функцію слід викликати лише з основного потоку.

Змінено в версії 3.5: У Windows функція тепер також підтримує ручки сокетів.

Виняткові класи

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.

Об’єкти винятків

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 returns NULL.

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 returns NULL.

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 by raise ... 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 or None. This steals a reference to cause.

The __suppress_context__ attribute is implicitly set to True 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 the except* clauses (so they have a different traceback from orig) and those that were reraised (and have the same traceback as orig). Return the ExceptionGroup that needs to be reraised in the end, or None if there is nothing to reraise.

Added in version 3.12.

Виняткові об’єкти 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.

Установіть для атрибута start даного об’єкта винятку значення start. Повертає 0 в разі успіху, -1 у випадку невдачі.

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 у випадку невдачі.

Контроль рекурсії

Ці дві функції забезпечують спосіб виконання безпечних рекурсивних викликів на рівні 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 using PyOS_CheckStack(). If this is the case, it sets a MemoryError and returns a nonzero value.

Потім функція перевіряє, чи досягнуто обмеження рекурсії. Якщо це так, встановлюється RecursionError і повертається ненульове значення. В іншому випадку повертається нуль.

де має бути рядок у кодуванні UTF-8, такий як " у перевірці екземпляра", який об’єднується з повідомленням RecursionError, спричиненим обмеженням глибини рекурсії.

Змінено в версії 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().

Змінено в версії 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(), який повертає нуль.

Стандартні винятки

All standard Python exceptions 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:

C Назва

Назва Python

Примітки

PyExc_BaseException

BaseException

[1]

PyExc_Exception

Exception

[1]

PyExc_ArithmeticError

ArithmeticError

[1]

PyExc_AssertionError

AssertionError

PyExc_AttributeError

AttributeError

PyExc_BlockingIOError

BlockingIOError

PyExc_BrokenPipeError

Помилка BrokenPipeError

PyExc_BufferError

BufferError

PyExc_ChildProcessError

ChildProcessError

PyExc_ConnectionAbortedError

ConnectionAbortedError

PyExc_ConnectionError

ConnectionError

PyExc_ConnectionRefusedError

ConnectionRefusedError

PyExc_ConnectionResetError

ConnectionResetError

PyExc_EOFError

EOFError

PyExc_FileExistsError

FileExistsError

PyExc_FileNotFoundError

FileNotFoundError

PyExc_FloatingPointError

FloatingPointError

PyExc_GeneratorExit

GeneratorExit

PyExc_ImportError

ImportError

PyExc_IndentationError

IndentationError

PyExc_IndexError

IndexError

PyExc_InterruptedError

InterruptedError

PyExc_IsADirectoryError

IsADirectoryError

PyExc_KeyError

KeyError

PyExc_KeyboardInterrupt

KeyboardInterrupt

PyExc_LookupError

LookupError

[1]

PyExc_MemoryError

помилка пам'яті

PyExc_ModuleNotFoundError

ModuleNotFoundError

PyExc_NameError

NameError

PyExc_NotADirectoryError

NotADirectoryError

PyExc_NotImplementedError

NotImplementedError

PyExc_OSError

OSError

[1]

PyExc_OverflowError

OverflowError

PyExc_PermissionError

PermissionError

PyExc_ProcessLookupError

ProcessLookupError

PyExc_RecursionError

RecursionError

PyExc_ReferenceError

ReferenceError

PyExc_RuntimeError

RuntimeError

PyExc_StopAsyncIteration

StopAsyncIteration

PyExc_StopIteration

StopIteration

PyExc_SyntaxError

SyntaxError

PyExc_SystemError

SystemError

PyExc_SystemExit

SystemError

PyExc_TabError

TabError

PyExc_TimeoutError

TimeoutError

PyExc_TypeError

TypeError

PyExc_UnboundLocalError

UnboundLocalError

PyExc_UnicodeDecodeError

Помилка UnicodeDecodeError

PyExc_UnicodeEncodeError

UnicodeEncodeError

PyExc_UnicodeError

Помилка Unicode

PyExc_UnicodeTranslateError

Помилка UnicodeTranslateError

PyExc_ValueError

ValueError

PyExc_ZeroDivisionError

Помилка ZeroDivisionError

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 і PyExc_TimeoutError були представлені після PEP 3151.

Added in version 3.5: PyExc_StopAsyncIteration і PyExc_RecursionError.

Added in version 3.6: PyExc_ModuleNotFoundError.

Це псевдоніми сумісності з PyExc_OSError:

C Назва

Примітки

PyExc_EnvironmentError

PyExc_IOError

PyExc_WindowsError

[2]

Змінено в версії 3.3: Раніше ці псевдоніми були окремими типами винятків.

Примітки:

Стандартні категорії попереджень

All standard Python 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:

C Назва

Назва Python

Примітки

PyExc_Warning

Warning

[3]

PyExc_BytesWarning

BytesWarning

PyExc_DeprecationWarning

DeprecationWarning

PyExc_FutureWarning

FutureWarning

PyExc_ImportWarning

ImportWarning

PyExc_PendingDeprecationWarning

PendingDeprecationWarning

PyExc_ResourceWarning

ResourceWarning

PyExc_RuntimeWarning

RuntimeWarning

PyExc_SyntaxWarning

SyntaxWarning

PyExc_UnicodeWarning

Попередження Unicode

PyExc_UserWarning

UserWarning

Added in version 3.2: PyExc_ResourceWarning.

Примітки: