blob: 68ac090f99ab73afb49c1f04345800977d8a2d11 [file] [log] [blame]
Georg Brandl116aa622007-08-15 14:28:22 +00001.. highlightlang:: c
2
3
4.. _exceptionhandling:
5
6******************
7Exception Handling
8******************
9
10The functions described in this chapter will let you handle and raise Python
11exceptions. It is important to understand some of the basics of Python
12exception handling. It works somewhat like the Unix :cdata:`errno` variable:
13there is a global indicator (per thread) of the last error that occurred. Most
14functions don't clear this on success, but will set it to indicate the cause of
15the error on failure. Most functions also return an error indicator, usually
16*NULL* if they are supposed to return a pointer, or ``-1`` if they return an
17integer (exception: the :cfunc:`PyArg_\*` functions return ``1`` for success and
18``0`` for failure).
19
20When a function must fail because some function it called failed, it generally
21doesn't set the error indicator; the function it called already set it. It is
22responsible for either handling the error and clearing the exception or
23returning after cleaning up any resources it holds (such as object references or
24memory allocations); it should *not* continue normally if it is not prepared to
25handle the error. If returning due to an error, it is important to indicate to
26the caller that an error has been set. If the error is not handled or carefully
27propagated, additional calls into the Python/C API may not behave as intended
28and may fail in mysterious ways.
29
30The error indicator consists of three Python objects corresponding to the result
31of ``sys.exc_info()``. API functions exist to interact with the error indicator
32in various ways. There is a separate error indicator for each thread.
33
34.. % XXX Order of these should be more thoughtful.
35.. % Either alphabetical or some kind of structure.
36
37
38.. cfunction:: void PyErr_Print()
39
40 Print a standard traceback to ``sys.stderr`` and clear the error indicator.
41 Call this function only when the error indicator is set. (Otherwise it will
42 cause a fatal error!)
43
44
45.. cfunction:: PyObject* PyErr_Occurred()
46
47 Test whether the error indicator is set. If set, return the exception *type*
48 (the first argument to the last call to one of the :cfunc:`PyErr_Set\*`
49 functions or to :cfunc:`PyErr_Restore`). If not set, return *NULL*. You do not
50 own a reference to the return value, so you do not need to :cfunc:`Py_DECREF`
51 it.
52
53 .. note::
54
55 Do not compare the return value to a specific exception; use
56 :cfunc:`PyErr_ExceptionMatches` instead, shown below. (The comparison could
57 easily fail since the exception may be an instance instead of a class, in the
58 case of a class exception, or it may the a subclass of the expected exception.)
59
60
61.. cfunction:: int PyErr_ExceptionMatches(PyObject *exc)
62
63 Equivalent to ``PyErr_GivenExceptionMatches(PyErr_Occurred(), exc)``. This
64 should only be called when an exception is actually set; a memory access
65 violation will occur if no exception has been raised.
66
67
68.. cfunction:: int PyErr_GivenExceptionMatches(PyObject *given, PyObject *exc)
69
70 Return true if the *given* exception matches the exception in *exc*. If *exc*
71 is a class object, this also returns true when *given* is an instance of a
72 subclass. If *exc* is a tuple, all exceptions in the tuple (and recursively in
73 subtuples) are searched for a match. If *given* is *NULL*, a memory access
74 violation will occur.
75
76
77.. cfunction:: void PyErr_NormalizeException(PyObject**exc, PyObject**val, PyObject**tb)
78
79 Under certain circumstances, the values returned by :cfunc:`PyErr_Fetch` below
80 can be "unnormalized", meaning that ``*exc`` is a class object but ``*val`` is
81 not an instance of the same class. This function can be used to instantiate
82 the class in that case. If the values are already normalized, nothing happens.
83 The delayed normalization is implemented to improve performance.
84
85
86.. cfunction:: void PyErr_Clear()
87
88 Clear the error indicator. If the error indicator is not set, there is no
89 effect.
90
91
92.. cfunction:: void PyErr_Fetch(PyObject **ptype, PyObject **pvalue, PyObject **ptraceback)
93
94 Retrieve the error indicator into three variables whose addresses are passed.
95 If the error indicator is not set, set all three variables to *NULL*. If it is
96 set, it will be cleared and you own a reference to each object retrieved. The
97 value and traceback object may be *NULL* even when the type object is not.
98
99 .. note::
100
101 This function is normally only used by code that needs to handle exceptions or
102 by code that needs to save and restore the error indicator temporarily.
103
104
105.. cfunction:: void PyErr_Restore(PyObject *type, PyObject *value, PyObject *traceback)
106
107 Set the error indicator from the three objects. If the error indicator is
108 already set, it is cleared first. If the objects are *NULL*, the error
109 indicator is cleared. Do not pass a *NULL* type and non-*NULL* value or
110 traceback. The exception type should be a class. Do not pass an invalid
111 exception type or value. (Violating these rules will cause subtle problems
112 later.) This call takes away a reference to each object: you must own a
113 reference to each object before the call and after the call you no longer own
114 these references. (If you don't understand this, don't use this function. I
115 warned you.)
116
117 .. note::
118
119 This function is normally only used by code that needs to save and restore the
120 error indicator temporarily; use :cfunc:`PyErr_Fetch` to save the current
121 exception state.
122
123
124.. cfunction:: void PyErr_SetString(PyObject *type, const char *message)
125
126 This is the most common way to set the error indicator. The first argument
127 specifies the exception type; it is normally one of the standard exceptions,
128 e.g. :cdata:`PyExc_RuntimeError`. You need not increment its reference count.
129 The second argument is an error message; it is converted to a string object.
130
131
132.. cfunction:: void PyErr_SetObject(PyObject *type, PyObject *value)
133
134 This function is similar to :cfunc:`PyErr_SetString` but lets you specify an
135 arbitrary Python object for the "value" of the exception.
136
137
138.. cfunction:: PyObject* PyErr_Format(PyObject *exception, const char *format, ...)
139
140 This function sets the error indicator and returns *NULL*. *exception* should be
141 a Python exception (class, not an instance). *format* should be a string,
142 containing format codes, similar to :cfunc:`printf`. The ``width.precision``
143 before a format code is parsed, but the width part is ignored.
144
145 .. % This should be exactly the same as the table in PyString_FromFormat.
146 .. % One should just refer to the other.
147 .. % The descriptions for %zd and %zu are wrong, but the truth is complicated
148 .. % because not all compilers support the %z width modifier -- we fake it
149 .. % when necessary via interpolating PY_FORMAT_SIZE_T.
150 .. % %u, %lu, %zu should have "new in Python 2.5" blurbs.
151
152 +-------------------+---------------+--------------------------------+
153 | Format Characters | Type | Comment |
154 +===================+===============+================================+
155 | :attr:`%%` | *n/a* | The literal % character. |
156 +-------------------+---------------+--------------------------------+
157 | :attr:`%c` | int | A single character, |
158 | | | represented as an C int. |
159 +-------------------+---------------+--------------------------------+
160 | :attr:`%d` | int | Exactly equivalent to |
161 | | | ``printf("%d")``. |
162 +-------------------+---------------+--------------------------------+
163 | :attr:`%u` | unsigned int | Exactly equivalent to |
164 | | | ``printf("%u")``. |
165 +-------------------+---------------+--------------------------------+
166 | :attr:`%ld` | long | Exactly equivalent to |
167 | | | ``printf("%ld")``. |
168 +-------------------+---------------+--------------------------------+
169 | :attr:`%lu` | unsigned long | Exactly equivalent to |
170 | | | ``printf("%lu")``. |
171 +-------------------+---------------+--------------------------------+
172 | :attr:`%zd` | Py_ssize_t | Exactly equivalent to |
173 | | | ``printf("%zd")``. |
174 +-------------------+---------------+--------------------------------+
175 | :attr:`%zu` | size_t | Exactly equivalent to |
176 | | | ``printf("%zu")``. |
177 +-------------------+---------------+--------------------------------+
178 | :attr:`%i` | int | Exactly equivalent to |
179 | | | ``printf("%i")``. |
180 +-------------------+---------------+--------------------------------+
181 | :attr:`%x` | int | Exactly equivalent to |
182 | | | ``printf("%x")``. |
183 +-------------------+---------------+--------------------------------+
184 | :attr:`%s` | char\* | A null-terminated C character |
185 | | | array. |
186 +-------------------+---------------+--------------------------------+
187 | :attr:`%p` | void\* | The hex representation of a C |
188 | | | pointer. Mostly equivalent to |
189 | | | ``printf("%p")`` except that |
190 | | | it is guaranteed to start with |
191 | | | the literal ``0x`` regardless |
192 | | | of what the platform's |
193 | | | ``printf`` yields. |
194 +-------------------+---------------+--------------------------------+
195
196 An unrecognized format character causes all the rest of the format string to be
197 copied as-is to the result string, and any extra arguments discarded.
198
199
200.. cfunction:: void PyErr_SetNone(PyObject *type)
201
202 This is a shorthand for ``PyErr_SetObject(type, Py_None)``.
203
204
205.. cfunction:: int PyErr_BadArgument()
206
207 This is a shorthand for ``PyErr_SetString(PyExc_TypeError, message)``, where
208 *message* indicates that a built-in operation was invoked with an illegal
209 argument. It is mostly for internal use.
210
211
212.. cfunction:: PyObject* PyErr_NoMemory()
213
214 This is a shorthand for ``PyErr_SetNone(PyExc_MemoryError)``; it returns *NULL*
215 so an object allocation function can write ``return PyErr_NoMemory();`` when it
216 runs out of memory.
217
218
219.. cfunction:: PyObject* PyErr_SetFromErrno(PyObject *type)
220
221 .. index:: single: strerror()
222
223 This is a convenience function to raise an exception when a C library function
224 has returned an error and set the C variable :cdata:`errno`. It constructs a
225 tuple object whose first item is the integer :cdata:`errno` value and whose
226 second item is the corresponding error message (gotten from :cfunc:`strerror`),
227 and then calls ``PyErr_SetObject(type, object)``. On Unix, when the
228 :cdata:`errno` value is :const:`EINTR`, indicating an interrupted system call,
229 this calls :cfunc:`PyErr_CheckSignals`, and if that set the error indicator,
230 leaves it set to that. The function always returns *NULL*, so a wrapper
231 function around a system call can write ``return PyErr_SetFromErrno(type);``
232 when the system call returns an error.
233
234
235.. cfunction:: PyObject* PyErr_SetFromErrnoWithFilename(PyObject *type, const char *filename)
236
237 Similar to :cfunc:`PyErr_SetFromErrno`, with the additional behavior that if
238 *filename* is not *NULL*, it is passed to the constructor of *type* as a third
239 parameter. In the case of exceptions such as :exc:`IOError` and :exc:`OSError`,
240 this is used to define the :attr:`filename` attribute of the exception instance.
241
242
243.. cfunction:: PyObject* PyErr_SetFromWindowsErr(int ierr)
244
245 This is a convenience function to raise :exc:`WindowsError`. If called with
246 *ierr* of :cdata:`0`, the error code returned by a call to :cfunc:`GetLastError`
247 is used instead. It calls the Win32 function :cfunc:`FormatMessage` to retrieve
248 the Windows description of error code given by *ierr* or :cfunc:`GetLastError`,
249 then it constructs a tuple object whose first item is the *ierr* value and whose
250 second item is the corresponding error message (gotten from
251 :cfunc:`FormatMessage`), and then calls ``PyErr_SetObject(PyExc_WindowsError,
252 object)``. This function always returns *NULL*. Availability: Windows.
253
254
255.. cfunction:: PyObject* PyErr_SetExcFromWindowsErr(PyObject *type, int ierr)
256
257 Similar to :cfunc:`PyErr_SetFromWindowsErr`, with an additional parameter
258 specifying the exception type to be raised. Availability: Windows.
259
260 .. versionadded:: 2.3
261
262
263.. cfunction:: PyObject* PyErr_SetFromWindowsErrWithFilename(int ierr, const char *filename)
264
265 Similar to :cfunc:`PyErr_SetFromWindowsErr`, with the additional behavior that
266 if *filename* is not *NULL*, it is passed to the constructor of
267 :exc:`WindowsError` as a third parameter. Availability: Windows.
268
269
270.. cfunction:: PyObject* PyErr_SetExcFromWindowsErrWithFilename(PyObject *type, int ierr, char *filename)
271
272 Similar to :cfunc:`PyErr_SetFromWindowsErrWithFilename`, with an additional
273 parameter specifying the exception type to be raised. Availability: Windows.
274
275 .. versionadded:: 2.3
276
277
278.. cfunction:: void PyErr_BadInternalCall()
279
280 This is a shorthand for ``PyErr_SetString(PyExc_TypeError, message)``, where
281 *message* indicates that an internal operation (e.g. a Python/C API function)
282 was invoked with an illegal argument. It is mostly for internal use.
283
284
285.. cfunction:: int PyErr_WarnEx(PyObject *category, char *message, int stacklevel)
286
287 Issue a warning message. The *category* argument is a warning category (see
288 below) or *NULL*; the *message* argument is a message string. *stacklevel* is a
289 positive number giving a number of stack frames; the warning will be issued from
290 the currently executing line of code in that stack frame. A *stacklevel* of 1
291 is the function calling :cfunc:`PyErr_WarnEx`, 2 is the function above that,
292 and so forth.
293
294 This function normally prints a warning message to *sys.stderr*; however, it is
295 also possible that the user has specified that warnings are to be turned into
296 errors, and in that case this will raise an exception. It is also possible that
297 the function raises an exception because of a problem with the warning machinery
298 (the implementation imports the :mod:`warnings` module to do the heavy lifting).
299 The return value is ``0`` if no exception is raised, or ``-1`` if an exception
300 is raised. (It is not possible to determine whether a warning message is
301 actually printed, nor what the reason is for the exception; this is
302 intentional.) If an exception is raised, the caller should do its normal
303 exception handling (for example, :cfunc:`Py_DECREF` owned references and return
304 an error value).
305
306 Warning categories must be subclasses of :cdata:`Warning`; the default warning
307 category is :cdata:`RuntimeWarning`. The standard Python warning categories are
308 available as global variables whose names are ``PyExc_`` followed by the Python
309 exception name. These have the type :ctype:`PyObject\*`; they are all class
310 objects. Their names are :cdata:`PyExc_Warning`, :cdata:`PyExc_UserWarning`,
311 :cdata:`PyExc_UnicodeWarning`, :cdata:`PyExc_DeprecationWarning`,
312 :cdata:`PyExc_SyntaxWarning`, :cdata:`PyExc_RuntimeWarning`, and
313 :cdata:`PyExc_FutureWarning`. :cdata:`PyExc_Warning` is a subclass of
314 :cdata:`PyExc_Exception`; the other warning categories are subclasses of
315 :cdata:`PyExc_Warning`.
316
317 For information about warning control, see the documentation for the
318 :mod:`warnings` module and the :option:`-W` option in the command line
319 documentation. There is no C API for warning control.
320
321
322.. cfunction:: int PyErr_WarnExplicit(PyObject *category, const char *message, const char *filename, int lineno, const char *module, PyObject *registry)
323
324 Issue a warning message with explicit control over all warning attributes. This
325 is a straightforward wrapper around the Python function
326 :func:`warnings.warn_explicit`, see there for more information. The *module*
327 and *registry* arguments may be set to *NULL* to get the default effect
328 described there.
329
330
331.. cfunction:: int PyErr_CheckSignals()
332
333 .. index::
334 module: signal
335 single: SIGINT
336 single: KeyboardInterrupt (built-in exception)
337
338 This function interacts with Python's signal handling. It checks whether a
339 signal has been sent to the processes and if so, invokes the corresponding
340 signal handler. If the :mod:`signal` module is supported, this can invoke a
341 signal handler written in Python. In all cases, the default effect for
342 :const:`SIGINT` is to raise the :exc:`KeyboardInterrupt` exception. If an
343 exception is raised the error indicator is set and the function returns ``-1``;
344 otherwise the function returns ``0``. The error indicator may or may not be
345 cleared if it was previously set.
346
347
348.. cfunction:: void PyErr_SetInterrupt()
349
350 .. index::
351 single: SIGINT
352 single: KeyboardInterrupt (built-in exception)
353
354 This function simulates the effect of a :const:`SIGINT` signal arriving --- the
355 next time :cfunc:`PyErr_CheckSignals` is called, :exc:`KeyboardInterrupt` will
356 be raised. It may be called without holding the interpreter lock.
357
358 .. % XXX This was described as obsolete, but is used in
359 .. % thread.interrupt_main() (used from IDLE), so it's still needed.
360
361
362.. cfunction:: PyObject* PyErr_NewException(char *name, PyObject *base, PyObject *dict)
363
364 This utility function creates and returns a new exception object. The *name*
365 argument must be the name of the new exception, a C string of the form
366 ``module.class``. The *base* and *dict* arguments are normally *NULL*. This
367 creates a class object derived from :exc:`Exception` (accessible in C as
368 :cdata:`PyExc_Exception`).
369
370 The :attr:`__module__` attribute of the new class is set to the first part (up
371 to the last dot) of the *name* argument, and the class name is set to the last
372 part (after the last dot). The *base* argument can be used to specify alternate
373 base classes; it can either be only one class or a tuple of classes. The *dict*
374 argument can be used to specify a dictionary of class variables and methods.
375
376
377.. cfunction:: void PyErr_WriteUnraisable(PyObject *obj)
378
379 This utility function prints a warning message to ``sys.stderr`` when an
380 exception has been set but it is impossible for the interpreter to actually
381 raise the exception. It is used, for example, when an exception occurs in an
382 :meth:`__del__` method.
383
384 The function is called with a single argument *obj* that identifies the context
385 in which the unraisable exception occurred. The repr of *obj* will be printed in
386 the warning message.
387
388
389.. _standardexceptions:
390
391Standard Exceptions
392===================
393
394All standard Python exceptions are available as global variables whose names are
395``PyExc_`` followed by the Python exception name. These have the type
396:ctype:`PyObject\*`; they are all class objects. For completeness, here are all
397the variables:
398
399+------------------------------------+----------------------------+----------+
400| C Name | Python Name | Notes |
401+====================================+============================+==========+
402| :cdata:`PyExc_BaseException` | :exc:`BaseException` | (1), (4) |
403+------------------------------------+----------------------------+----------+
404| :cdata:`PyExc_Exception` | :exc:`Exception` | \(1) |
405+------------------------------------+----------------------------+----------+
406| :cdata:`PyExc_ArithmeticError` | :exc:`ArithmeticError` | \(1) |
407+------------------------------------+----------------------------+----------+
408| :cdata:`PyExc_LookupError` | :exc:`LookupError` | \(1) |
409+------------------------------------+----------------------------+----------+
410| :cdata:`PyExc_AssertionError` | :exc:`AssertionError` | |
411+------------------------------------+----------------------------+----------+
412| :cdata:`PyExc_AttributeError` | :exc:`AttributeError` | |
413+------------------------------------+----------------------------+----------+
414| :cdata:`PyExc_EOFError` | :exc:`EOFError` | |
415+------------------------------------+----------------------------+----------+
416| :cdata:`PyExc_EnvironmentError` | :exc:`EnvironmentError` | \(1) |
417+------------------------------------+----------------------------+----------+
418| :cdata:`PyExc_FloatingPointError` | :exc:`FloatingPointError` | |
419+------------------------------------+----------------------------+----------+
420| :cdata:`PyExc_IOError` | :exc:`IOError` | |
421+------------------------------------+----------------------------+----------+
422| :cdata:`PyExc_ImportError` | :exc:`ImportError` | |
423+------------------------------------+----------------------------+----------+
424| :cdata:`PyExc_IndexError` | :exc:`IndexError` | |
425+------------------------------------+----------------------------+----------+
426| :cdata:`PyExc_KeyError` | :exc:`KeyError` | |
427+------------------------------------+----------------------------+----------+
428| :cdata:`PyExc_KeyboardInterrupt` | :exc:`KeyboardInterrupt` | |
429+------------------------------------+----------------------------+----------+
430| :cdata:`PyExc_MemoryError` | :exc:`MemoryError` | |
431+------------------------------------+----------------------------+----------+
432| :cdata:`PyExc_NameError` | :exc:`NameError` | |
433+------------------------------------+----------------------------+----------+
434| :cdata:`PyExc_NotImplementedError` | :exc:`NotImplementedError` | |
435+------------------------------------+----------------------------+----------+
436| :cdata:`PyExc_OSError` | :exc:`OSError` | |
437+------------------------------------+----------------------------+----------+
438| :cdata:`PyExc_OverflowError` | :exc:`OverflowError` | |
439+------------------------------------+----------------------------+----------+
440| :cdata:`PyExc_ReferenceError` | :exc:`ReferenceError` | \(2) |
441+------------------------------------+----------------------------+----------+
442| :cdata:`PyExc_RuntimeError` | :exc:`RuntimeError` | |
443+------------------------------------+----------------------------+----------+
444| :cdata:`PyExc_SyntaxError` | :exc:`SyntaxError` | |
445+------------------------------------+----------------------------+----------+
446| :cdata:`PyExc_SystemError` | :exc:`SystemError` | |
447+------------------------------------+----------------------------+----------+
448| :cdata:`PyExc_SystemExit` | :exc:`SystemExit` | |
449+------------------------------------+----------------------------+----------+
450| :cdata:`PyExc_TypeError` | :exc:`TypeError` | |
451+------------------------------------+----------------------------+----------+
452| :cdata:`PyExc_ValueError` | :exc:`ValueError` | |
453+------------------------------------+----------------------------+----------+
454| :cdata:`PyExc_WindowsError` | :exc:`WindowsError` | \(3) |
455+------------------------------------+----------------------------+----------+
456| :cdata:`PyExc_ZeroDivisionError` | :exc:`ZeroDivisionError` | |
457+------------------------------------+----------------------------+----------+
458
459.. index::
460 single: PyExc_BaseException
461 single: PyExc_Exception
462 single: PyExc_ArithmeticError
463 single: PyExc_LookupError
464 single: PyExc_AssertionError
465 single: PyExc_AttributeError
466 single: PyExc_EOFError
467 single: PyExc_EnvironmentError
468 single: PyExc_FloatingPointError
469 single: PyExc_IOError
470 single: PyExc_ImportError
471 single: PyExc_IndexError
472 single: PyExc_KeyError
473 single: PyExc_KeyboardInterrupt
474 single: PyExc_MemoryError
475 single: PyExc_NameError
476 single: PyExc_NotImplementedError
477 single: PyExc_OSError
478 single: PyExc_OverflowError
479 single: PyExc_ReferenceError
480 single: PyExc_RuntimeError
481 single: PyExc_SyntaxError
482 single: PyExc_SystemError
483 single: PyExc_SystemExit
484 single: PyExc_TypeError
485 single: PyExc_ValueError
486 single: PyExc_WindowsError
487 single: PyExc_ZeroDivisionError
488
489Notes:
490
491(1)
492 This is a base class for other standard exceptions.
493
494(2)
495 This is the same as :exc:`weakref.ReferenceError`.
496
497(3)
498 Only defined on Windows; protect code that uses this by testing that the
499 preprocessor macro ``MS_WINDOWS`` is defined.
500
501(4)
502 .. versionadded:: 2.5
503
504
505Deprecation of String Exceptions
506================================
507
508.. index:: single: BaseException (built-in exception)
509
510All exceptions built into Python or provided in the standard library are derived
511from :exc:`BaseException`.
512
513String exceptions are still supported in the interpreter to allow existing code
514to run unmodified, but this will also change in a future release.
515