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