Added 'list_only' option (and modified 'run()' to respect it).
[python/dscho.git] / Doc / lib / libexcs.tex
blobfb80b7603a9a4d821d06d426e76731a97f7081fd
1 \section{Built-in Exceptions}
3 \declaremodule{standard}{exceptions}
4 \modulesynopsis{Standard exceptions classes.}
7 Exceptions can be class objects or string objects. While
8 traditionally, most exceptions have been string objects, in Python
9 1.5, all standard exceptions have been converted to class objects,
10 and users are encouraged to do the same. The source code for those
11 exceptions is present in the standard library module
12 \module{exceptions}; this module never needs to be imported explicitly.
14 For backward compatibility, when Python is invoked with the \code{-X}
15 option, most of the standard exceptions are strings\footnote{For
16 forward-compatibility the new exceptions \exception{Exception},
17 \exception{LookupError},
18 \exception{ArithmeticError}, \exception{EnvironmentError}, and
19 \exception{StandardError} are tuples.}. This option may be used to
20 run code that breaks because of the different semantics of class based
21 exceptions. The \code{-X} option will become obsolete in future
22 Python versions, so the recommended solution is to fix the code.
24 Two distinct string objects with the same value are considered different
25 exceptions. This is done to force programmers to use exception names
26 rather than their string value when specifying exception handlers.
27 The string value of all built-in exceptions is their name, but this is
28 not a requirement for user-defined exceptions or exceptions defined by
29 library modules.
31 For class exceptions, in a \keyword{try} statement with an \keyword{except}
32 clause that mentions a particular class, that clause also handles
33 any exception classes derived from that class (but not exception
34 classes from which \emph{it} is derived). Two exception classes
35 that are not related via subclassing are never equivalent, even if
36 they have the same name.
37 \stindex{try}
38 \stindex{except}
40 The built-in exceptions listed below can be generated by the
41 interpreter or built-in functions. Except where mentioned, they have
42 an ``associated value'' indicating the detailed cause of the error.
43 This may be a string or a tuple containing several items of
44 information (e.g., an error code and a string explaining the code).
45 The associated value is the second argument to the \keyword{raise}
46 statement. For string exceptions, the associated value itself will be
47 stored in the variable named as the second argument of the
48 \keyword{except} clause (if any). For class exceptions, that variable
49 receives the exception instance. If the exception class is derived
50 from the standard root class \exception{Exception}, the associated
51 value is present as the exception instance's \member{args} attribute,
52 and possibly on other attributes as well.
53 \stindex{raise}
55 User code can raise built-in exceptions. This can be used to test an
56 exception handler or to report an error condition ``just like'' the
57 situation in which the interpreter raises the same exception; but
58 beware that there is nothing to prevent user code from raising an
59 inappropriate error.
61 \setindexsubitem{(built-in exception base class)}
63 The following exceptions are only used as base classes for other
64 exceptions. When string-based standard exceptions are used, they
65 are tuples containing the directly derived classes.
67 \begin{excdesc}{Exception}
68 The root class for exceptions. All built-in exceptions are derived
69 from this class. All user-defined exceptions should also be derived
70 from this class, but this is not (yet) enforced. The \function{str()}
71 function, when applied to an instance of this class (or most derived
72 classes) returns the string value of the argument or arguments, or an
73 empty string if no arguments were given to the constructor. When used
74 as a sequence, this accesses the arguments given to the constructor
75 (handy for backward compatibility with old code). The arguments are
76 also available on the instance's \member{args} attribute, as a tuple.
77 \end{excdesc}
79 \begin{excdesc}{StandardError}
80 The base class for all built-in exceptions except
81 \exception{SystemExit}. \exception{StandardError} itself is derived
82 from the root class
83 \exception{Exception}.
84 \end{excdesc}
86 \begin{excdesc}{ArithmeticError}
87 The base class for those built-in exceptions that are raised for
88 various arithmetic errors: \exception{OverflowError},
89 \exception{ZeroDivisionError}, \exception{FloatingPointError}.
90 \end{excdesc}
92 \begin{excdesc}{LookupError}
93 The base class for the exceptions that are raised when a key or
94 index used on a mapping or sequence is invalid: \exception{IndexError},
95 \exception{KeyError}.
96 \end{excdesc}
98 \begin{excdesc}{EnvironmentError}
99 The base class for exceptions that
100 can occur outside the Python system: \exception{IOError},
101 \exception{OSError}. When exceptions of this type are created with a
102 2-tuple, the first item is available on the instance's \member{errno}
103 attribute (it is assumed to be an error number), and the second item
104 is available on the \member{strerror} attribute (it is usually the
105 associated error message). The tuple itself is also available on the
106 \member{args} attribute.
107 \versionadded{1.5.2}
109 When an \exception{EnvironmentError} exception is instantiated with a
110 3-tuple, the first two items are available as above, while the third
111 item is available on the \member{filename} attribute. However, for
112 backwards compatibility, the \member{args} attribute contains only a
113 2-tuple of the first two constructor arguments.
115 The \member{filename} attribute is \code{None} when this exception is
116 created with other than 3 arguments. The \member{errno} and
117 \member{strerror} attributes are also \code{None} when the instance was
118 created with other than 2 or 3 arguments. In this last case,
119 \member{args} contains the verbatim constructor arguments as a tuple.
120 \end{excdesc}
122 \setindexsubitem{(built-in exception)}
124 The following exceptions are the exceptions that are actually raised.
125 They are class objects, except when the \code{-X} option is used to
126 revert back to string-based standard exceptions.
128 \begin{excdesc}{AssertionError}
129 Raised when an \keyword{assert} statement fails.
130 \stindex{assert}
131 \end{excdesc}
133 \begin{excdesc}{AttributeError}
134 % xref to attribute reference?
135 Raised when an attribute reference or assignment fails. (When an
136 object does not support attribute references or attribute assignments
137 at all, \exception{TypeError} is raised.)
138 \end{excdesc}
140 \begin{excdesc}{EOFError}
141 % XXXJH xrefs here
142 Raised when one of the built-in functions (\function{input()} or
143 \function{raw_input()}) hits an end-of-file condition (\EOF{}) without
144 reading any data.
145 % XXXJH xrefs here
146 (N.B.: the \method{read()} and \method{readline()} methods of file
147 objects return an empty string when they hit \EOF{}.)
148 \end{excdesc}
150 \begin{excdesc}{FloatingPointError}
151 Raised when a floating point operation fails. This exception is
152 always defined, but can only be raised when Python is configured
153 with the \code{--with-fpectl} option, or the
154 \constant{WANT_SIGFPE_HANDLER} symbol is defined in the
155 \file{config.h} file.
156 \end{excdesc}
158 \begin{excdesc}{IOError}
159 % XXXJH xrefs here
160 Raised when an I/O operation (such as a \keyword{print} statement,
161 the built-in \function{open()} function or a method of a file
162 object) fails for an I/O-related reason, e.g., ``file not found'' or
163 ``disk full''.
165 This class is derived from \exception{EnvironmentError}. See the
166 discussion above for more information on exception instance
167 attributes.
168 \end{excdesc}
170 \begin{excdesc}{ImportError}
171 % XXXJH xref to import statement?
172 Raised when an \keyword{import} statement fails to find the module
173 definition or when a \code{from \textrm{\ldots} import} fails to find a
174 name that is to be imported.
175 \end{excdesc}
177 \begin{excdesc}{IndexError}
178 % XXXJH xref to sequences
179 Raised when a sequence subscript is out of range. (Slice indices are
180 silently truncated to fall in the allowed range; if an index is not a
181 plain integer, \exception{TypeError} is raised.)
182 \end{excdesc}
184 \begin{excdesc}{KeyError}
185 % XXXJH xref to mapping objects?
186 Raised when a mapping (dictionary) key is not found in the set of
187 existing keys.
188 \end{excdesc}
190 \begin{excdesc}{KeyboardInterrupt}
191 Raised when the user hits the interrupt key (normally
192 \kbd{Control-C} or \kbd{DEL}). During execution, a check for
193 interrupts is made regularly.
194 % XXXJH xrefs here
195 Interrupts typed when a built-in function \function{input()} or
196 \function{raw_input()}) is waiting for input also raise this
197 exception.
198 \end{excdesc}
200 \begin{excdesc}{MemoryError}
201 Raised when an operation runs out of memory but the situation may
202 still be rescued (by deleting some objects). The associated value is
203 a string indicating what kind of (internal) operation ran out of memory.
204 Note that because of the underlying memory management architecture
205 (\C{}'s \cfunction{malloc()} function), the interpreter may not
206 always be able to completely recover from this situation; it
207 nevertheless raises an exception so that a stack traceback can be
208 printed, in case a run-away program was the cause.
209 \end{excdesc}
211 \begin{excdesc}{NameError}
212 Raised when a local or global name is not found. This applies only
213 to unqualified names. The associated value is the name that could
214 not be found.
215 \end{excdesc}
217 \begin{excdesc}{NotImplementedError}
218 This exception is derived from \exception{RuntimeError}. In user
219 defined base classes, abstract methods should raise this exception
220 when they require derived classes to override the method.
221 \versionadded{1.5.2}
222 \end{excdesc}
224 \begin{excdesc}{OSError}
225 %xref for os module
226 This class is derived from \exception{EnvironmentError} and is used
227 primarily as the \refmodule{os} module's \code{os.error} exception.
228 See \exception{EnvironmentError} above for a description of the
229 possible associated values.
230 \versionadded{1.5.2}
231 \end{excdesc}
233 \begin{excdesc}{OverflowError}
234 % XXXJH reference to long's and/or int's?
235 Raised when the result of an arithmetic operation is too large to be
236 represented. This cannot occur for long integers (which would rather
237 raise \exception{MemoryError} than give up). Because of the lack of
238 standardization of floating point exception handling in \C{}, most
239 floating point operations also aren't checked. For plain integers,
240 all operations that can overflow are checked except left shift, where
241 typical applications prefer to drop bits than raise an exception.
242 \end{excdesc}
244 \begin{excdesc}{RuntimeError}
245 Raised when an error is detected that doesn't fall in any of the
246 other categories. The associated value is a string indicating what
247 precisely went wrong. (This exception is mostly a relic from a
248 previous version of the interpreter; it is not used very much any
249 more.)
250 \end{excdesc}
252 \begin{excdesc}{SyntaxError}
253 % XXXJH xref to these functions?
254 Raised when the parser encounters a syntax error. This may occur in
255 an \keyword{import} statement, in an \keyword{exec} statement, in a call
256 to the built-in function \function{eval()} or \function{input()}, or
257 when reading the initial script or standard input (also
258 interactively).
260 When class exceptions are used, instances of this class have
261 atttributes \member{filename}, \member{lineno}, \member{offset} and
262 \member{text} for easier access to the details; for string exceptions,
263 the associated value is usually a tuple of the form
264 \code{(message, (filename, lineno, offset, text))}.
265 For class exceptions, \function{str()} returns only the message.
266 \end{excdesc}
268 \begin{excdesc}{SystemError}
269 Raised when the interpreter finds an internal error, but the
270 situation does not look so serious to cause it to abandon all hope.
271 The associated value is a string indicating what went wrong (in
272 low-level terms).
274 You should report this to the author or maintainer of your Python
275 interpreter. Be sure to report the version string of the Python
276 interpreter (\code{sys.version}; it is also printed at the start of an
277 interactive Python session), the exact error message (the exception's
278 associated value) and if possible the source of the program that
279 triggered the error.
280 \end{excdesc}
282 \begin{excdesc}{SystemExit}
283 % XXXJH xref to module sys?
284 This exception is raised by the \function{sys.exit()} function. When it
285 is not handled, the Python interpreter exits; no stack traceback is
286 printed. If the associated value is a plain integer, it specifies the
287 system exit status (passed to \C{}'s \cfunction{exit()} function); if it is
288 \code{None}, the exit status is zero; if it has another type (such as
289 a string), the object's value is printed and the exit status is one.
291 When class exceptions are used, the instance has an attribute
292 \member{code} which is set to the proposed exit status or error message
293 (defaulting to \code{None}). Also, this exception derives directly
294 from \exception{Exception} and not \exception{StandardError}, since it
295 is not technically an error.
297 A call to \function{sys.exit()} is translated into an exception so that
298 clean-up handlers (\keyword{finally} clauses of \keyword{try} statements)
299 can be executed, and so that a debugger can execute a script without
300 running the risk of losing control. The \function{os._exit()} function
301 can be used if it is absolutely positively necessary to exit
302 immediately (e.g., after a \function{fork()} in the child process).
303 \end{excdesc}
305 \begin{excdesc}{TypeError}
306 Raised when a built-in operation or function is applied to an object
307 of inappropriate type. The associated value is a string giving
308 details about the type mismatch.
309 \end{excdesc}
311 \begin{excdesc}{ValueError}
312 Raised when a built-in operation or function receives an argument
313 that has the right type but an inappropriate value, and the
314 situation is not described by a more precise exception such as
315 \exception{IndexError}.
316 \end{excdesc}
318 \begin{excdesc}{ZeroDivisionError}
319 Raised when the second argument of a division or modulo operation is
320 zero. The associated value is a string indicating the type of the
321 operands and the operation.
322 \end{excdesc}