blob: 355e6fb302df0885722b61259099ae1a08d67d81 [file] [log] [blame]
Fred Drake3adf79e2001-10-12 19:01:43 +00001\chapter{Exception Handling \label{exceptionHandling}}
2
3The functions described in this chapter will let you handle and raise Python
4exceptions. It is important to understand some of the basics of
5Python exception handling. It works somewhat like the
6\UNIX{} \cdata{errno} variable: there is a global indicator (per
7thread) of the last error that occurred. Most functions don't clear
8this on success, but will set it to indicate the cause of the error on
9failure. Most functions also return an error indicator, usually
10\NULL{} if they are supposed to return a pointer, or \code{-1} if they
11return an integer (exception: the \cfunction{PyArg_Parse*()} functions
12return \code{1} for success and \code{0} for failure). When a
13function must fail because some function it called failed, it
14generally doesn't set the error indicator; the function it called
15already set it.
16
17The error indicator consists of three Python objects corresponding to
18\withsubitem{(in module sys)}{
19 \ttindex{exc_type}\ttindex{exc_value}\ttindex{exc_traceback}}
20the Python variables \code{sys.exc_type}, \code{sys.exc_value} and
21\code{sys.exc_traceback}. API functions exist to interact with the
22error indicator in various ways. There is a separate error indicator
23for each thread.
24
25% XXX Order of these should be more thoughtful.
26% Either alphabetical or some kind of structure.
27
28\begin{cfuncdesc}{void}{PyErr_Print}{}
29 Print a standard traceback to \code{sys.stderr} and clear the error
30 indicator. Call this function only when the error indicator is
31 set. (Otherwise it will cause a fatal error!)
32\end{cfuncdesc}
33
34\begin{cfuncdesc}{PyObject*}{PyErr_Occurred}{}
35 Test whether the error indicator is set. If set, return the
36 exception \emph{type} (the first argument to the last call to one of
37 the \cfunction{PyErr_Set*()} functions or to
38 \cfunction{PyErr_Restore()}). If not set, return \NULL. You do
39 not own a reference to the return value, so you do not need to
40 \cfunction{Py_DECREF()} it. \note{Do not compare the return value
41 to a specific exception; use \cfunction{PyErr_ExceptionMatches()}
42 instead, shown below. (The comparison could easily fail since the
43 exception may be an instance instead of a class, in the case of a
44 class exception, or it may the a subclass of the expected
45 exception.)}
46\end{cfuncdesc}
47
48\begin{cfuncdesc}{int}{PyErr_ExceptionMatches}{PyObject *exc}
49 Equivalent to \samp{PyErr_GivenExceptionMatches(PyErr_Occurred(),
50 \var{exc})}. This should only be called when an exception is
51 actually set; a memory access violation will occur if no exception
52 has been raised.
53\end{cfuncdesc}
54
55\begin{cfuncdesc}{int}{PyErr_GivenExceptionMatches}{PyObject *given, PyObject *exc}
56 Return true if the \var{given} exception matches the exception in
57 \var{exc}. If \var{exc} is a class object, this also returns true
58 when \var{given} is an instance of a subclass. If \var{exc} is a
59 tuple, all exceptions in the tuple (and recursively in subtuples)
60 are searched for a match. If \var{given} is \NULL, a memory access
61 violation will occur.
62\end{cfuncdesc}
63
64\begin{cfuncdesc}{void}{PyErr_NormalizeException}{PyObject**exc, PyObject**val, PyObject**tb}
65 Under certain circumstances, the values returned by
66 \cfunction{PyErr_Fetch()} below can be ``unnormalized'', meaning
67 that \code{*\var{exc}} is a class object but \code{*\var{val}} is
68 not an instance of the same class. This function can be used to
69 instantiate the class in that case. If the values are already
70 normalized, nothing happens. The delayed normalization is
71 implemented to improve performance.
72\end{cfuncdesc}
73
74\begin{cfuncdesc}{void}{PyErr_Clear}{}
75 Clear the error indicator. If the error indicator is not set, there
76 is no effect.
77\end{cfuncdesc}
78
79\begin{cfuncdesc}{void}{PyErr_Fetch}{PyObject **ptype, PyObject **pvalue,
80 PyObject **ptraceback}
81 Retrieve the error indicator into three variables whose addresses
82 are passed. If the error indicator is not set, set all three
83 variables to \NULL. If it is set, it will be cleared and you own a
84 reference to each object retrieved. The value and traceback object
85 may be \NULL{} even when the type object is not. \note{This
86 function is normally only used by code that needs to handle
87 exceptions or by code that needs to save and restore the error
88 indicator temporarily.}
89\end{cfuncdesc}
90
91\begin{cfuncdesc}{void}{PyErr_Restore}{PyObject *type, PyObject *value,
92 PyObject *traceback}
93 Set the error indicator from the three objects. If the error
94 indicator is already set, it is cleared first. If the objects are
95 \NULL, the error indicator is cleared. Do not pass a \NULL{} type
96 and non-\NULL{} value or traceback. The exception type should be a
97 string or class; if it is a class, the value should be an instance
98 of that class. Do not pass an invalid exception type or value.
99 (Violating these rules will cause subtle problems later.) This call
100 takes away a reference to each object: you must own a reference to
101 each object before the call and after the call you no longer own
102 these references. (If you don't understand this, don't use this
103 function. I warned you.) \note{This function is normally only used
104 by code that needs to save and restore the error indicator
105 temporarily.}
106\end{cfuncdesc}
107
108\begin{cfuncdesc}{void}{PyErr_SetString}{PyObject *type, char *message}
109 This is the most common way to set the error indicator. The first
110 argument specifies the exception type; it is normally one of the
111 standard exceptions, e.g. \cdata{PyExc_RuntimeError}. You need not
112 increment its reference count. The second argument is an error
113 message; it is converted to a string object.
114\end{cfuncdesc}
115
116\begin{cfuncdesc}{void}{PyErr_SetObject}{PyObject *type, PyObject *value}
117 This function is similar to \cfunction{PyErr_SetString()} but lets
118 you specify an arbitrary Python object for the ``value'' of the
119 exception. You need not increment its reference count.
120\end{cfuncdesc}
121
122\begin{cfuncdesc}{PyObject*}{PyErr_Format}{PyObject *exception,
123 const char *format, \moreargs}
124 This function sets the error indicator. \var{exception} should be a
125 Python exception (string or class, not an instance). \var{format}
126 should be a string, containing format codes, similar to
127 \cfunction{printf()}. The \code{width.precision} before a format
128 code is parsed, but the width part is ignored.
129
130 \begin{tableii}{c|l}{character}{Character}{Meaning}
131 \lineii{c}{Character, as an \ctype{int} parameter}
132 \lineii{d}{Number in decimal, as an \ctype{int} parameter}
133 \lineii{x}{Number in hexadecimal, as an \ctype{int} parameter}
134 \lineii{x}{A string, as a \ctype{char *} parameter}
135 \end{tableii}
136
137 An unrecognized format character causes all the rest of the format
138 string to be copied as-is to the result string, and any extra
139 arguments discarded.
140
141 A new reference is returned, which is owned by the caller.
142\end{cfuncdesc}
143
144\begin{cfuncdesc}{void}{PyErr_SetNone}{PyObject *type}
145 This is a shorthand for \samp{PyErr_SetObject(\var{type},
146 Py_None)}.
147\end{cfuncdesc}
148
149\begin{cfuncdesc}{int}{PyErr_BadArgument}{}
150 This is a shorthand for \samp{PyErr_SetString(PyExc_TypeError,
151 \var{message})}, where \var{message} indicates that a built-in
152 operation was invoked with an illegal argument. It is mostly for
153 internal use.
154\end{cfuncdesc}
155
156\begin{cfuncdesc}{PyObject*}{PyErr_NoMemory}{}
157 This is a shorthand for \samp{PyErr_SetNone(PyExc_MemoryError)}; it
158 returns \NULL{} so an object allocation function can write
159 \samp{return PyErr_NoMemory();} when it runs out of memory.
160\end{cfuncdesc}
161
162\begin{cfuncdesc}{PyObject*}{PyErr_SetFromErrno}{PyObject *type}
163 This is a convenience function to raise an exception when a C
164 library function has returned an error and set the C variable
165 \cdata{errno}. It constructs a tuple object whose first item is the
166 integer \cdata{errno} value and whose second item is the
167 corresponding error message (gotten from
168 \cfunction{strerror()}\ttindex{strerror()}), and then calls
169 \samp{PyErr_SetObject(\var{type}, \var{object})}. On \UNIX, when
170 the \cdata{errno} value is \constant{EINTR}, indicating an
171 interrupted system call, this calls
172 \cfunction{PyErr_CheckSignals()}, and if that set the error
173 indicator, leaves it set to that. The function always returns
174 \NULL, so a wrapper function around a system call can write
175 \samp{return PyErr_SetFromErrno();} when the system call returns an
176 error.
177\end{cfuncdesc}
178
179\begin{cfuncdesc}{PyObject*}{PyErr_SetFromErrnoWithFilename}{PyObject *type,
180 char *filename}
181 Similar to \cfunction{PyErr_SetFromErrno()}, with the additional
182 behavior that if \var{filename} is not \NULL, it is passed to the
183 constructor of \var{type} as a third parameter. In the case of
184 exceptions such as \exception{IOError} and \exception{OSError}, this
185 is used to define the \member{filename} attribute of the exception
186 instance.
187\end{cfuncdesc}
188
189\begin{cfuncdesc}{void}{PyErr_BadInternalCall}{}
190 This is a shorthand for \samp{PyErr_SetString(PyExc_TypeError,
191 \var{message})}, where \var{message} indicates that an internal
192 operation (e.g. a Python/C API function) was invoked with an illegal
193 argument. It is mostly for internal use.
194\end{cfuncdesc}
195
196\begin{cfuncdesc}{int}{PyErr_Warn}{PyObject *category, char *message}
197 Issue a warning message. The \var{category} argument is a warning
198 category (see below) or \NULL; the \var{message} argument is a
199 message string.
200
201 This function normally prints a warning message to \var{sys.stderr};
202 however, it is also possible that the user has specified that
203 warnings are to be turned into errors, and in that case this will
204 raise an exception. It is also possible that the function raises an
205 exception because of a problem with the warning machinery (the
206 implementation imports the \module{warnings} module to do the heavy
207 lifting). The return value is \code{0} if no exception is raised,
208 or \code{-1} if an exception is raised. (It is not possible to
209 determine whether a warning message is actually printed, nor what
210 the reason is for the exception; this is intentional.) If an
211 exception is raised, the caller should do its normal exception
212 handling (for example, \cfunction{Py_DECREF()} owned references and
213 return an error value).
214
215 Warning categories must be subclasses of \cdata{Warning}; the
216 default warning category is \cdata{RuntimeWarning}. The standard
217 Python warning categories are available as global variables whose
218 names are \samp{PyExc_} followed by the Python exception name.
219 These have the type \ctype{PyObject*}; they are all class objects.
220 Their names are \cdata{PyExc_Warning}, \cdata{PyExc_UserWarning},
221 \cdata{PyExc_DeprecationWarning}, \cdata{PyExc_SyntaxWarning}, and
222 \cdata{PyExc_RuntimeWarning}. \cdata{PyExc_Warning} is a subclass
223 of \cdata{PyExc_Exception}; the other warning categories are
224 subclasses of \cdata{PyExc_Warning}.
225
226 For information about warning control, see the documentation for the
227 \module{warnings} module and the \programopt{-W} option in the
228 command line documentation. There is no C API for warning control.
229\end{cfuncdesc}
230
231\begin{cfuncdesc}{int}{PyErr_WarnExplicit}{PyObject *category, char *message,
232 char *filename, int lineno, char *module, PyObject *registry}
233 Issue a warning message with explicit control over all warning
234 attributes. This is a straightforward wrapper around the Python
235 function \function{warnings.warn_explicit()}, see there for more
236 information. The \var{module} and \var{registry} arguments may be
237 set to \NULL{} to get the default effect described there.
238\end{cfuncdesc}
239
240\begin{cfuncdesc}{int}{PyErr_CheckSignals}{}
241 This function interacts with Python's signal handling. It checks
242 whether a signal has been sent to the processes and if so, invokes
243 the corresponding signal handler. If the
244 \module{signal}\refbimodindex{signal} module is supported, this can
245 invoke a signal handler written in Python. In all cases, the
246 default effect for \constant{SIGINT}\ttindex{SIGINT} is to raise the
247 \withsubitem{(built-in exception)}{\ttindex{KeyboardInterrupt}}
248 \exception{KeyboardInterrupt} exception. If an exception is raised
249 the error indicator is set and the function returns \code{1};
250 otherwise the function returns \code{0}. The error indicator may or
251 may not be cleared if it was previously set.
252\end{cfuncdesc}
253
254\begin{cfuncdesc}{void}{PyErr_SetInterrupt}{}
255 This function is obsolete. It simulates the effect of a
256 \constant{SIGINT}\ttindex{SIGINT} signal arriving --- the next time
257 \cfunction{PyErr_CheckSignals()} is called,
258 \withsubitem{(built-in exception)}{\ttindex{KeyboardInterrupt}}
259 \exception{KeyboardInterrupt} will be raised. It may be called
260 without holding the interpreter lock.
261\end{cfuncdesc}
262
263\begin{cfuncdesc}{PyObject*}{PyErr_NewException}{char *name,
264 PyObject *base,
265 PyObject *dict}
266 This utility function creates and returns a new exception object.
267 The \var{name} argument must be the name of the new exception, a C
268 string of the form \code{module.class}. The \var{base} and
269 \var{dict} arguments are normally \NULL. This creates a class
270 object derived from the root for all exceptions, the built-in name
271 \exception{Exception} (accessible in C as \cdata{PyExc_Exception}).
272 The \member{__module__} attribute of the new class is set to the
273 first part (up to the last dot) of the \var{name} argument, and the
274 class name is set to the last part (after the last dot). The
275 \var{base} argument can be used to specify an alternate base class.
276 The \var{dict} argument can be used to specify a dictionary of class
277 variables and methods.
278\end{cfuncdesc}
279
280\begin{cfuncdesc}{void}{PyErr_WriteUnraisable}{PyObject *obj}
281 This utility function prints a warning message to \code{sys.stderr}
282 when an exception has been set but it is impossible for the
283 interpreter to actually raise the exception. It is used, for
284 example, when an exception occurs in an \method{__del__()} method.
285
286 The function is called with a single argument \var{obj} that
287 identifies where the context in which the unraisable exception
288 occurred. The repr of \var{obj} will be printed in the warning
289 message.
290\end{cfuncdesc}
291
292\section{Standard Exceptions \label{standardExceptions}}
293
294All standard Python exceptions are available as global variables whose
295names are \samp{PyExc_} followed by the Python exception name. These
296have the type \ctype{PyObject*}; they are all class objects. For
297completeness, here are all the variables:
298
299\begin{tableiii}{l|l|c}{cdata}{C Name}{Python Name}{Notes}
300 \lineiii{PyExc_Exception}{\exception{Exception}}{(1)}
301 \lineiii{PyExc_StandardError}{\exception{StandardError}}{(1)}
302 \lineiii{PyExc_ArithmeticError}{\exception{ArithmeticError}}{(1)}
303 \lineiii{PyExc_LookupError}{\exception{LookupError}}{(1)}
304 \lineiii{PyExc_AssertionError}{\exception{AssertionError}}{}
305 \lineiii{PyExc_AttributeError}{\exception{AttributeError}}{}
306 \lineiii{PyExc_EOFError}{\exception{EOFError}}{}
307 \lineiii{PyExc_EnvironmentError}{\exception{EnvironmentError}}{(1)}
308 \lineiii{PyExc_FloatingPointError}{\exception{FloatingPointError}}{}
309 \lineiii{PyExc_IOError}{\exception{IOError}}{}
310 \lineiii{PyExc_ImportError}{\exception{ImportError}}{}
311 \lineiii{PyExc_IndexError}{\exception{IndexError}}{}
312 \lineiii{PyExc_KeyError}{\exception{KeyError}}{}
313 \lineiii{PyExc_KeyboardInterrupt}{\exception{KeyboardInterrupt}}{}
314 \lineiii{PyExc_MemoryError}{\exception{MemoryError}}{}
315 \lineiii{PyExc_NameError}{\exception{NameError}}{}
316 \lineiii{PyExc_NotImplementedError}{\exception{NotImplementedError}}{}
317 \lineiii{PyExc_OSError}{\exception{OSError}}{}
318 \lineiii{PyExc_OverflowError}{\exception{OverflowError}}{}
319 \lineiii{PyExc_ReferenceError}{\exception{ReferenceError}}{(2)}
320 \lineiii{PyExc_RuntimeError}{\exception{RuntimeError}}{}
321 \lineiii{PyExc_SyntaxError}{\exception{SyntaxError}}{}
322 \lineiii{PyExc_SystemError}{\exception{SystemError}}{}
323 \lineiii{PyExc_SystemExit}{\exception{SystemExit}}{}
324 \lineiii{PyExc_TypeError}{\exception{TypeError}}{}
325 \lineiii{PyExc_ValueError}{\exception{ValueError}}{}
326 \lineiii{PyExc_WindowsError}{\exception{WindowsError}}{(3)}
327 \lineiii{PyExc_ZeroDivisionError}{\exception{ZeroDivisionError}}{}
328\end{tableiii}
329
330\noindent
331Notes:
332\begin{description}
333\item[(1)]
334 This is a base class for other standard exceptions.
335
336\item[(2)]
337 This is the same as \exception{weakref.ReferenceError}.
338
339\item[(3)]
340 Only defined on Windows; protect code that uses this by testing that
341 the preprocessor macro \code{MS_WINDOWS} is defined.
342\end{description}
343
344
345\section{Deprecation of String Exceptions}
346
347All exceptions built into Python or provided in the standard library
348are derived from \exception{Exception}.
349\withsubitem{(built-in exception)}{\ttindex{Exception}}
350
351String exceptions are still supported in the interpreter to allow
352existing code to run unmodified, but this will also change in a future
353release.