append(): Fixing the test for convertability after consultation with
[python/dscho.git] / Doc / lib / libexcs.tex
blob54b141a9a1490ff62ebb26d4878a7c59ab22e757
1 \section{Built-in Exceptions}
3 \declaremodule{standard}{exceptions}
4 \modulesynopsis{Standard exceptions classes.}
7 Exceptions can be class objects or string objects. Though most
8 exceptions have been string objects in past versions of Python, in
9 Python 1.5 and newer versions, all standard exceptions have been
10 converted to class objects, and users are encouraged to do the same.
11 The exceptions are defined in the module \module{exceptions}. This
12 module never needs to be imported explicitly: the exceptions are
13 provided in the built-in namespace as well as the \module{exceptions}
14 module.
16 Two distinct string objects with the same value are considered different
17 exceptions. This is done to force programmers to use exception names
18 rather than their string value when specifying exception handlers.
19 The string value of all built-in exceptions is their name, but this is
20 not a requirement for user-defined exceptions or exceptions defined by
21 library modules.
23 For class exceptions, in a \keyword{try}\stindex{try} statement with
24 an \keyword{except}\stindex{except} clause that mentions a particular
25 class, that clause also handles any exception classes derived from
26 that class (but not exception classes from which \emph{it} is
27 derived). Two exception classes that are not related via subclassing
28 are never equivalent, even if they have the same name.
30 The built-in exceptions listed below can be generated by the
31 interpreter or built-in functions. Except where mentioned, they have
32 an ``associated value'' indicating the detailed cause of the error.
33 This may be a string or a tuple containing several items of
34 information (e.g., an error code and a string explaining the code).
35 The associated value is the second argument to the
36 \keyword{raise}\stindex{raise} statement. For string exceptions, the
37 associated value itself will be stored in the variable named as the
38 second argument of the \keyword{except} clause (if any). For class
39 exceptions, that variable receives the exception instance. If the
40 exception class is derived from the standard root class
41 \exception{Exception}, the associated value is present as the
42 exception instance's \member{args} attribute, and possibly on other
43 attributes as well.
45 User code can raise built-in exceptions. This can be used to test an
46 exception handler or to report an error condition ``just like'' the
47 situation in which the interpreter raises the same exception; but
48 beware that there is nothing to prevent user code from raising an
49 inappropriate error.
51 The built-in exception classes can be sub-classed to define new
52 exceptions; programmers are encouraged to at least derive new
53 exceptions from the \exception{Exception} base class. More
54 information on defining exceptions is available in the
55 \citetitle[../tut/tut.html]{Python Tutorial} under the heading
56 ``User-defined Exceptions.''
58 \setindexsubitem{(built-in exception base class)}
60 The following exceptions are only used as base classes for other
61 exceptions.
63 \begin{excdesc}{Exception}
64 The root class for exceptions. All built-in exceptions are derived
65 from this class. All user-defined exceptions should also be derived
66 from this class, but this is not (yet) enforced. The \function{str()}
67 function, when applied to an instance of this class (or most derived
68 classes) returns the string value of the argument or arguments, or an
69 empty string if no arguments were given to the constructor. When used
70 as a sequence, this accesses the arguments given to the constructor
71 (handy for backward compatibility with old code). The arguments are
72 also available on the instance's \member{args} attribute, as a tuple.
73 \end{excdesc}
75 \begin{excdesc}{StandardError}
76 The base class for all built-in exceptions except
77 \exception{StopIteration} and \exception{SystemExit}.
78 \exception{StandardError} itself is derived from the root class
79 \exception{Exception}.
80 \end{excdesc}
82 \begin{excdesc}{ArithmeticError}
83 The base class for those built-in exceptions that are raised for
84 various arithmetic errors: \exception{OverflowError},
85 \exception{ZeroDivisionError}, \exception{FloatingPointError}.
86 \end{excdesc}
88 \begin{excdesc}{LookupError}
89 The base class for the exceptions that are raised when a key or
90 index used on a mapping or sequence is invalid: \exception{IndexError},
91 \exception{KeyError}. This can be raised directly by
92 \function{sys.setdefaultencoding()}.
93 \end{excdesc}
95 \begin{excdesc}{EnvironmentError}
96 The base class for exceptions that
97 can occur outside the Python system: \exception{IOError},
98 \exception{OSError}. When exceptions of this type are created with a
99 2-tuple, the first item is available on the instance's \member{errno}
100 attribute (it is assumed to be an error number), and the second item
101 is available on the \member{strerror} attribute (it is usually the
102 associated error message). The tuple itself is also available on the
103 \member{args} attribute.
104 \versionadded{1.5.2}
106 When an \exception{EnvironmentError} exception is instantiated with a
107 3-tuple, the first two items are available as above, while the third
108 item is available on the \member{filename} attribute. However, for
109 backwards compatibility, the \member{args} attribute contains only a
110 2-tuple of the first two constructor arguments.
112 The \member{filename} attribute is \code{None} when this exception is
113 created with other than 3 arguments. The \member{errno} and
114 \member{strerror} attributes are also \code{None} when the instance was
115 created with other than 2 or 3 arguments. In this last case,
116 \member{args} contains the verbatim constructor arguments as a tuple.
117 \end{excdesc}
120 \setindexsubitem{(built-in exception)}
122 The following exceptions are the exceptions that are actually raised.
124 \begin{excdesc}{AssertionError}
125 \stindex{assert}
126 Raised when an \keyword{assert} statement fails.
127 \end{excdesc}
129 \begin{excdesc}{AttributeError}
130 % xref to attribute reference?
131 Raised when an attribute reference or assignment fails. (When an
132 object does not support attribute references or attribute assignments
133 at all, \exception{TypeError} is raised.)
134 \end{excdesc}
136 \begin{excdesc}{EOFError}
137 % XXXJH xrefs here
138 Raised when one of the built-in functions (\function{input()} or
139 \function{raw_input()}) hits an end-of-file condition (\EOF) without
140 reading any data.
141 % XXXJH xrefs here
142 (N.B.: the \method{read()} and \method{readline()} methods of file
143 objects return an empty string when they hit \EOF.)
144 \end{excdesc}
146 \begin{excdesc}{FloatingPointError}
147 Raised when a floating point operation fails. This exception is
148 always defined, but can only be raised when Python is configured
149 with the \longprogramopt{with-fpectl} option, or the
150 \constant{WANT_SIGFPE_HANDLER} symbol is defined in the
151 \file{pyconfig.h} file.
152 \end{excdesc}
154 \begin{excdesc}{IOError}
155 % XXXJH xrefs here
156 Raised when an I/O operation (such as a \keyword{print} statement,
157 the built-in \function{open()} function or a method of a file
158 object) fails for an I/O-related reason, e.g., ``file not found'' or
159 ``disk full''.
161 This class is derived from \exception{EnvironmentError}. See the
162 discussion above for more information on exception instance
163 attributes.
164 \end{excdesc}
166 \begin{excdesc}{ImportError}
167 % XXXJH xref to import statement?
168 Raised when an \keyword{import} statement fails to find the module
169 definition or when a \code{from \textrm{\ldots} import} fails to find a
170 name that is to be imported.
171 \end{excdesc}
173 \begin{excdesc}{IndexError}
174 % XXXJH xref to sequences
175 Raised when a sequence subscript is out of range. (Slice indices are
176 silently truncated to fall in the allowed range; if an index is not a
177 plain integer, \exception{TypeError} is raised.)
178 \end{excdesc}
180 \begin{excdesc}{KeyError}
181 % XXXJH xref to mapping objects?
182 Raised when a mapping (dictionary) key is not found in the set of
183 existing keys.
184 \end{excdesc}
186 \begin{excdesc}{KeyboardInterrupt}
187 Raised when the user hits the interrupt key (normally
188 \kbd{Control-C} or \kbd{Delete}). During execution, a check for
189 interrupts is made regularly.
190 % XXXJH xrefs here
191 Interrupts typed when a built-in function \function{input()} or
192 \function{raw_input()}) is waiting for input also raise this
193 exception.
194 \end{excdesc}
196 \begin{excdesc}{MemoryError}
197 Raised when an operation runs out of memory but the situation may
198 still be rescued (by deleting some objects). The associated value is
199 a string indicating what kind of (internal) operation ran out of memory.
200 Note that because of the underlying memory management architecture
201 (C's \cfunction{malloc()} function), the interpreter may not
202 always be able to completely recover from this situation; it
203 nevertheless raises an exception so that a stack traceback can be
204 printed, in case a run-away program was the cause.
205 \end{excdesc}
207 \begin{excdesc}{NameError}
208 Raised when a local or global name is not found. This applies only
209 to unqualified names. The associated value is an error message that
210 includes the name that could not be found.
211 \end{excdesc}
213 \begin{excdesc}{NotImplementedError}
214 This exception is derived from \exception{RuntimeError}. In user
215 defined base classes, abstract methods should raise this exception
216 when they require derived classes to override the method.
217 \versionadded{1.5.2}
218 \end{excdesc}
220 \begin{excdesc}{OSError}
221 %xref for os module
222 This class is derived from \exception{EnvironmentError} and is used
223 primarily as the \refmodule{os} module's \code{os.error} exception.
224 See \exception{EnvironmentError} above for a description of the
225 possible associated values.
226 \versionadded{1.5.2}
227 \end{excdesc}
229 \begin{excdesc}{OverflowError}
230 % XXXJH reference to long's and/or int's?
231 Raised when the result of an arithmetic operation is too large to be
232 represented. This cannot occur for long integers (which would rather
233 raise \exception{MemoryError} than give up). Because of the lack of
234 standardization of floating point exception handling in C, most
235 floating point operations also aren't checked. For plain integers,
236 all operations that can overflow are checked except left shift, where
237 typical applications prefer to drop bits than raise an exception.
238 \end{excdesc}
240 \begin{excdesc}{ReferenceError}
241 This exception is raised when a weak reference proxy, created by the
242 \function{\refmodule{weakref}.proxy()} function, is used to access
243 an attribute of the referent after it has been garbage collected.
244 For more information on weak references, see the \refmodule{weakref}
245 module.
246 \versionadded[Previously known as the
247 \exception{\refmodule{weakref}.ReferenceError}
248 exception]{2.2}
249 \end{excdesc}
251 \begin{excdesc}{RuntimeError}
252 Raised when an error is detected that doesn't fall in any of the
253 other categories. The associated value is a string indicating what
254 precisely went wrong. (This exception is mostly a relic from a
255 previous version of the interpreter; it is not used very much any
256 more.)
257 \end{excdesc}
259 \begin{excdesc}{StopIteration}
260 Raised by an iterator's \method{next()} method to signal that there
261 are no further values.
262 This is derived from \exception{Exception} rather than
263 \exception{StandardError}, since this is not considered an error in
264 its normal application.
265 \versionadded{2.2}
266 \end{excdesc}
268 \begin{excdesc}{SyntaxError}
269 % XXXJH xref to these functions?
270 Raised when the parser encounters a syntax error. This may occur in
271 an \keyword{import} statement, in an \keyword{exec} statement, in a call
272 to the built-in function \function{eval()} or \function{input()}, or
273 when reading the initial script or standard input (also
274 interactively).
276 Instances of this class have atttributes \member{filename},
277 \member{lineno}, \member{offset} and \member{text} for easier access
278 to the details. \function{str()} of the exception instance returns
279 only the message.
280 \end{excdesc}
282 \begin{excdesc}{SystemError}
283 Raised when the interpreter finds an internal error, but the
284 situation does not look so serious to cause it to abandon all hope.
285 The associated value is a string indicating what went wrong (in
286 low-level terms).
288 You should report this to the author or maintainer of your Python
289 interpreter. Be sure to report the version of the Python
290 interpreter (\code{sys.version}; it is also printed at the start of an
291 interactive Python session), the exact error message (the exception's
292 associated value) and if possible the source of the program that
293 triggered the error.
294 \end{excdesc}
296 \begin{excdesc}{SystemExit}
297 % XXXJH xref to module sys?
298 This exception is raised by the \function{sys.exit()} function. When it
299 is not handled, the Python interpreter exits; no stack traceback is
300 printed. If the associated value is a plain integer, it specifies the
301 system exit status (passed to C's \cfunction{exit()} function); if it is
302 \code{None}, the exit status is zero; if it has another type (such as
303 a string), the object's value is printed and the exit status is one.
305 Instances have an attribute \member{code} which is set to the
306 proposed exit status or error message (defaulting to \code{None}).
307 Also, this exception derives directly from \exception{Exception} and
308 not \exception{StandardError}, since it is not technically an error.
310 A call to \function{sys.exit()} is translated into an exception so that
311 clean-up handlers (\keyword{finally} clauses of \keyword{try} statements)
312 can be executed, and so that a debugger can execute a script without
313 running the risk of losing control. The \function{os._exit()} function
314 can be used if it is absolutely positively necessary to exit
315 immediately (for example, in the child process after a call to
316 \function{fork()}).
317 \end{excdesc}
319 \begin{excdesc}{TypeError}
320 Raised when a built-in operation or function is applied to an object
321 of inappropriate type. The associated value is a string giving
322 details about the type mismatch.
323 \end{excdesc}
325 \begin{excdesc}{UnboundLocalError}
326 Raised when a reference is made to a local variable in a function or
327 method, but no value has been bound to that variable. This is a
328 subclass of \exception{NameError}.
329 \versionadded{2.0}
330 \end{excdesc}
332 \begin{excdesc}{UnicodeError}
333 Raised when a Unicode-related encoding or decoding error occurs. It
334 is a subclass of \exception{ValueError}.
335 \versionadded{2.0}
336 \end{excdesc}
338 \begin{excdesc}{UnicodeEncodeError}
339 Raised when a Unicode-related error occurs during encoding. It
340 is a subclass of \exception{UnicodeError}.
341 \versionadded{2.3}
342 \end{excdesc}
344 \begin{excdesc}{UnicodeDecodeError}
345 Raised when a Unicode-related error occurs during decoding. It
346 is a subclass of \exception{UnicodeError}.
347 \versionadded{2.3}
348 \end{excdesc}
350 \begin{excdesc}{UnicodeTranslateError}
351 Raised when a Unicode-related error occurs during translating. It
352 is a subclass of \exception{UnicodeError}.
353 \versionadded{2.3}
354 \end{excdesc}
356 \begin{excdesc}{ValueError}
357 Raised when a built-in operation or function receives an argument
358 that has the right type but an inappropriate value, and the
359 situation is not described by a more precise exception such as
360 \exception{IndexError}.
361 \end{excdesc}
363 \begin{excdesc}{WindowsError}
364 Raised when a Windows-specific error occurs or when the error number
365 does not correspond to an \cdata{errno} value. The
366 \member{errno} and \member{strerror} values are created from the
367 return values of the \cfunction{GetLastError()} and
368 \cfunction{FormatMessage()} functions from the Windows Platform API.
369 This is a subclass of \exception{OSError}.
370 \versionadded{2.0}
371 \end{excdesc}
373 \begin{excdesc}{ZeroDivisionError}
374 Raised when the second argument of a division or modulo operation is
375 zero. The associated value is a string indicating the type of the
376 operands and the operation.
377 \end{excdesc}
380 \setindexsubitem{(built-in warning)}
382 The following exceptions are used as warning categories; see the
383 \refmodule{warnings} module for more information.
385 \begin{excdesc}{Warning}
386 Base class for warning categories.
387 \end{excdesc}
389 \begin{excdesc}{UserWarning}
390 Base class for warnings generated by user code.
391 \end{excdesc}
393 \begin{excdesc}{DeprecationWarning}
394 Base class for warnings about deprecated features.
395 \end{excdesc}
397 \begin{excdesc}{PendingDeprecationWarning}
398 Base class for warnings about features which will be deprecated in the future.
399 \end{excdesc}
401 \begin{excdesc}{SyntaxWarning}
402 Base class for warnings about dubious syntax
403 \end{excdesc}
405 \begin{excdesc}{RuntimeWarning}
406 Base class for warnings about dubious runtime behavior.
407 \end{excdesc}
409 \begin{excdesc}{FutureWarning}
410 Base class for warnings about constructs that will change semantically
411 in the future.
412 \end{excdesc}
414 The class hierarchy for built-in exceptions is:
416 \begin{verbatim}
417 Exception
418 +-- SystemExit
419 +-- StopIteration
420 +-- StandardError
421 | +-- KeyboardInterrupt
422 | +-- ImportError
423 | +-- EnvironmentError
424 | | +-- IOError
425 | | +-- OSError
426 | | +-- WindowsError
427 | +-- EOFError
428 | +-- RuntimeError
429 | | +-- NotImplementedError
430 | +-- NameError
431 | | +-- UnboundLocalError
432 | +-- AttributeError
433 | +-- SyntaxError
434 | | +-- IndentationError
435 | | +-- TabError
436 | +-- TypeError
437 | +-- AssertionError
438 | +-- LookupError
439 | | +-- IndexError
440 | | +-- KeyError
441 | +-- ArithmeticError
442 | | +-- OverflowError
443 | | +-- ZeroDivisionError
444 | | +-- FloatingPointError
445 | +-- ValueError
446 | | +-- UnicodeError
447 | | +-- UnicodeEncodeError
448 | | +-- UnicodeDecodeError
449 | | +-- UnicodeTranslateError
450 | +-- ReferenceError
451 | +-- SystemError
452 | +-- MemoryError
453 +---Warning
454 +-- UserWarning
455 +-- DeprecationWarning
456 +-- PendingDeprecationWarning
457 +-- SyntaxWarning
458 +-- OverflowWarning
459 +-- RuntimeWarning
460 +-- FutureWarning
461 \end{verbatim}