1from .object cimport PyObject 2 3cdef extern from "Python.h": 4 5 ##################################################################### 6 # 3. Exception Handling 7 ##################################################################### 8 9 # The functions described in this chapter will let you handle and 10 # raise Python exceptions. It is important to understand some of 11 # the basics of Python exception handling. It works somewhat like 12 # the Unix errno variable: there is a global indicator (per 13 # thread) of the last error that occurred. Most functions don't 14 # clear this on success, but will set it to indicate the cause of 15 # the error on failure. Most functions also return an error 16 # indicator, usually NULL if they are supposed to return a 17 # pointer, or -1 if they return an integer (exception: the 18 # PyArg_*() functions return 1 for success and 0 for failure). 19 20 # When a function must fail because some function it called 21 # failed, it generally doesn't set the error indicator; the 22 # function it called already set it. It is responsible for either 23 # handling the error and clearing the exception or returning after 24 # cleaning up any resources it holds (such as object references or 25 # memory allocations); it should not continue normally if it is 26 # not prepared to handle the error. If returning due to an error, 27 # it is important to indicate to the caller that an error has been 28 # set. If the error is not handled or carefully propagated, 29 # additional calls into the Python/C API may not behave as 30 # intended and may fail in mysterious ways. 31 32 # The error indicator consists of three Python objects 33 # corresponding to the Python variables sys.exc_type, 34 # sys.exc_value and sys.exc_traceback. API functions exist to 35 # interact with the error indicator in various ways. There is a 36 # separate error indicator for each thread. 37 38 void PyErr_Print() 39 # Print a standard traceback to sys.stderr and clear the error 40 # indicator. Call this function only when the error indicator is 41 # set. (Otherwise it will cause a fatal error!) 42 43 PyObject* PyErr_Occurred() 44 # Return value: Borrowed reference. 45 # Test whether the error indicator is set. If set, return the 46 # exception type (the first argument to the last call to one of 47 # the PyErr_Set*() functions or to PyErr_Restore()). If not set, 48 # return NULL. You do not own a reference to the return value, so 49 # you do not need to Py_DECREF() it. Note: Do not compare the 50 # return value to a specific exception; use 51 # PyErr_ExceptionMatches() instead, shown below. (The comparison 52 # could easily fail since the exception may be an instance instead 53 # of a class, in the case of a class exception, or it may be a 54 # subclass of the expected exception.) 55 56 bint PyErr_ExceptionMatches(object exc) 57 # Equivalent to "PyErr_GivenExceptionMatches(PyErr_Occurred(), 58 # exc)". This should only be called when an exception is actually 59 # set; a memory access violation will occur if no exception has 60 # been raised. 61 62 bint PyErr_GivenExceptionMatches(object given, object exc) 63 # Return true if the given exception matches the exception in 64 # exc. If exc is a class object, this also returns true when given 65 # is an instance of a subclass. If exc is a tuple, all exceptions 66 # in the tuple (and recursively in subtuples) are searched for a 67 # match. If given is NULL, a memory access violation will occur. 68 69 void PyErr_NormalizeException(PyObject** exc, PyObject** val, PyObject** tb) 70 # Under certain circumstances, the values returned by 71 # PyErr_Fetch() below can be ``unnormalized'', meaning that *exc 72 # is a class object but *val is not an instance of the same 73 # class. This function can be used to instantiate the class in 74 # that case. If the values are already normalized, nothing 75 # happens. The delayed normalization is implemented to improve 76 # performance. 77 78 void PyErr_Clear() 79 # Clear the error indicator. If the error indicator is not set, there is no effect. 80 81 void PyErr_Fetch(PyObject** ptype, PyObject** pvalue, PyObject** ptraceback) 82 # Retrieve the error indicator into three variables whose 83 # addresses are passed. If the error indicator is not set, set all 84 # three variables to NULL. If it is set, it will be cleared and 85 # you own a reference to each object retrieved. The value and 86 # traceback object may be NULL even when the type object is 87 # not. Note: This function is normally only used by code that 88 # needs to handle exceptions or by code that needs to save and 89 # restore the error indicator temporarily. 90 91 void PyErr_Restore(PyObject* type, PyObject* value, PyObject* traceback) 92 # Set the error indicator from the three objects. If the error 93 # indicator is already set, it is cleared first. If the objects 94 # are NULL, the error indicator is cleared. Do not pass a NULL 95 # type and non-NULL value or traceback. The exception type should 96 # be a class. Do not pass an invalid exception type or 97 # value. (Violating these rules will cause subtle problems later.) 98 # This call takes away a reference to each object: you must own a 99 # reference to each object before the call and after the call you 100 # no longer own these references. (If you don't understand this, 101 # don't use this function. I warned you.) Note: This function is 102 # normally only used by code that needs to save and restore the 103 # error indicator temporarily; use PyErr_Fetch() to save the 104 # current exception state. 105 106 void PyErr_SetString(object type, char *message) 107 # This is the most common way to set the error indicator. The 108 # first argument specifies the exception type; it is normally one 109 # of the standard exceptions, e.g. PyExc_RuntimeError. You need 110 # not increment its reference count. The second argument is an 111 # error message; it is converted to a string object. 112 113 void PyErr_SetObject(object type, object value) 114 # This function is similar to PyErr_SetString() but lets you 115 # specify an arbitrary Python object for the ``value'' of the 116 # exception. 117 118 PyObject* PyErr_Format(object exception, char *format, ...) except NULL 119 # Return value: Always NULL. 120 # This function sets the error indicator and returns 121 # NULL. exception should be a Python exception (class, not an 122 # instance). format should be a string, containing format codes, 123 # similar to printf(). The width.precision before a format code is 124 # parsed, but the width part is ignored. 125 126 void PyErr_SetNone(object type) 127 # This is a shorthand for "PyErr_SetObject(type, Py_None)". 128 129 int PyErr_BadArgument() except 0 130 131 # This is a shorthand for "PyErr_SetString(PyExc_TypeError, 132 # message)", where message indicates that a built-in operation was 133 # invoked with an illegal argument. It is mostly for internal use. 134 135 PyObject* PyErr_NoMemory() except NULL 136 # Return value: Always NULL. 137 # This is a shorthand for "PyErr_SetNone(PyExc_MemoryError)"; it 138 # returns NULL so an object allocation function can write "return 139 # PyErr_NoMemory();" when it runs out of memory. 140 141 PyObject* PyErr_SetFromErrno(object type) except NULL 142 # Return value: Always NULL. 143 # This is a convenience function to raise an exception when a C 144 # library function has returned an error and set the C variable 145 # errno. It constructs a tuple object whose first item is the 146 # integer errno value and whose second item is the corresponding 147 # error message (gotten from strerror()), and then calls 148 # "PyErr_SetObject(type, object)". On Unix, when the errno value 149 # is EINTR, indicating an interrupted system call, this calls 150 # PyErr_CheckSignals(), and if that set the error indicator, 151 # leaves it set to that. The function always returns NULL, so a 152 # wrapper function around a system call can write "return 153 # PyErr_SetFromErrno(type);" when the system call returns an 154 # error. 155 156 PyObject* PyErr_SetFromErrnoWithFilenameObject(object type, object filenameObject) except NULL 157 # Similar to PyErr_SetFromErrno(), with the additional behavior 158 # that if filenameObject is not NULL, it is passed to the 159 # constructor of type as a third parameter. 160 # In the case of OSError exception, this is used to define 161 # the filename attribute of the exception instance. 162 163 PyObject* PyErr_SetFromErrnoWithFilename(object type, char *filename) except NULL 164 # Return value: Always NULL. Similar to PyErr_SetFromErrno(), 165 # with the additional behavior that if filename is not NULL, it is 166 # passed to the constructor of type as a third parameter. In the 167 # case of exceptions such as IOError and OSError, this is used to 168 # define the filename attribute of the exception instance. 169 170 PyObject* PyErr_SetFromWindowsErr(int ierr) except NULL 171 # Return value: Always NULL. This is a convenience function to 172 # raise WindowsError. If called with ierr of 0, the error code 173 # returned by a call to GetLastError() is used instead. It calls 174 # the Win32 function FormatMessage() to retrieve the Windows 175 # description of error code given by ierr or GetLastError(), then 176 # it constructs a tuple object whose first item is the ierr value 177 # and whose second item is the corresponding error message (gotten 178 # from FormatMessage()), and then calls 179 # "PyErr_SetObject(PyExc_WindowsError, object)". This function 180 # always returns NULL. Availability: Windows. 181 182 PyObject* PyErr_SetExcFromWindowsErr(object type, int ierr) except NULL 183 # Return value: Always NULL. Similar to 184 # PyErr_SetFromWindowsErr(), with an additional parameter 185 # specifying the exception type to be raised. Availability: 186 # Windows. New in version 2.3. 187 188 PyObject* PyErr_SetFromWindowsErrWithFilename(int ierr, char *filename) except NULL 189 # Return value: Always NULL. Similar to 190 # PyErr_SetFromWindowsErr(), with the additional behavior that if 191 # filename is not NULL, it is passed to the constructor of 192 # WindowsError as a third parameter. Availability: Windows. 193 194 PyObject* PyErr_SetExcFromWindowsErrWithFilename(object type, int ierr, char *filename) except NULL 195 # Return value: Always NULL. 196 # Similar to PyErr_SetFromWindowsErrWithFilename(), with an 197 # additional parameter specifying the exception type to be 198 # raised. Availability: Windows. 199 200 void PyErr_BadInternalCall() 201 # This is a shorthand for "PyErr_SetString(PyExc_TypeError, 202 # message)", where message indicates that an internal operation 203 # (e.g. a Python/C API function) was invoked with an illegal 204 # argument. It is mostly for internal use. 205 206 int PyErr_WarnEx(object category, char *message, int stacklevel) except -1 207 # Issue a warning message. The category argument is a warning 208 # category (see below) or NULL; the message argument is a message 209 # string. stacklevel is a positive number giving a number of stack 210 # frames; the warning will be issued from the currently executing 211 # line of code in that stack frame. A stacklevel of 1 is the 212 # function calling PyErr_WarnEx(), 2 is the function above that, 213 # and so forth. 214 215 int PyErr_WarnExplicit(object category, char *message, char *filename, int lineno, char *module, object registry) except -1 216 # Issue a warning message with explicit control over all warning 217 # attributes. This is a straightforward wrapper around the Python 218 # function warnings.warn_explicit(), see there for more 219 # information. The module and registry arguments may be set to 220 # NULL to get the default effect described there. 221 222 int PyErr_CheckSignals() except -1 223 # This function interacts with Python's signal handling. It checks 224 # whether a signal has been sent to the processes and if so, 225 # invokes the corresponding signal handler. If the signal module 226 # is supported, this can invoke a signal handler written in 227 # Python. In all cases, the default effect for SIGINT is to raise 228 # the KeyboardInterrupt exception. If an exception is raised the 229 # error indicator is set and the function returns 1; otherwise the 230 # function returns 0. The error indicator may or may not be 231 # cleared if it was previously set. 232 233 void PyErr_SetInterrupt() nogil 234 # This function simulates the effect of a SIGINT signal arriving 235 # -- the next time PyErr_CheckSignals() is called, 236 # KeyboardInterrupt will be raised. It may be called without 237 # holding the interpreter lock. 238 239 object PyErr_NewException(char *name, object base, object dict) 240 # Return value: New reference. 241 # This utility function creates and returns a new exception 242 # object. The name argument must be the name of the new exception, 243 # a C string of the form module.class. The base and dict arguments 244 # are normally NULL. This creates a class object derived from 245 # Exception (accessible in C as PyExc_Exception). 246 247 void PyErr_WriteUnraisable(object obj) 248 # This utility function prints a warning message to sys.stderr 249 # when an exception has been set but it is impossible for the 250 # interpreter to actually raise the exception. It is used, for 251 # example, when an exception occurs in an __del__() method. 252 # 253 # The function is called with a single argument obj that 254 # identifies the context in which the unraisable exception 255 # occurred. The repr of obj will be printed in the warning 256 # message. 257 258