source: vendor/python/2.5/Doc/lib/libexcs.tex

Last change on this file was 3225, checked in by bird, 18 years ago

Python 2.5

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