blob: e5dba345887e15bfe67497bff440f2aa5b813df5 [file] [log] [blame]
Guido van Rossum5fdeeea1994-01-02 01:22:07 +00001\section{Built-in Exceptions}
2
Guido van Rossumdf3dba01997-10-05 18:51:26 +00003Exceptions can be class objects or string objects. While
4traditionally, most exceptions have been string objects, in Python
51.5a4, all standard exceptions have been converted to class objects,
6and users are encouraged to the the same. The source code for those
7exceptions is present in the standard library module
8\code{exceptions}; this module never needs to be imported explicitly.
Guido van Rossum5fdeeea1994-01-02 01:22:07 +00009
Guido van Rossumdf3dba01997-10-05 18:51:26 +000010For backward compatibility, when Python is invoked with the \code{-X}
11option, the standard exceptions are strings. This may be needed to
12run some code that breaks because of the different semantics of class
13based exceptions. The \code{-X} option will become obsolete in future
14Python versions, so the recommended solution is to fix the code.
15
16Two distinct string objects with the same value are considered different
17exceptions. This is done to force programmers to use exception names
18rather than their string value when specifying exception handlers.
19The string value of all built-in exceptions is their name, but this is
20not a requirement for user-defined exceptions or exceptions defined by
21library modules.
22
23For class exceptions, in a \code{try} statement with an\code{except}
24clause that mentions a particular class, that clause also handles
25any exception classes derived from that class (but not exception
26classes from which \emph{it} is derived). Two exception classes
27that are not related via subclassing are never equivalent, even if
28they have the same name.
29\stindex{try}
30\stindex{except}
31
32The built-in exceptions listed below can be generated by the
33interpreter or built-in functions. Except where mentioned, they have
34an ``associated value'' indicating the detailed cause of the error.
35This may be a string or a tuple containing several items of
36information (e.g., an error code and a string explaining the code).
37The associated value is the second argument to the \code{raise}
38statement. For string exceptions, the associated value itself will be
39stored in the variable named as the second argument of the
40\code{except} clause (if any). For class exceptions derived from
41the root class \code{Exception}, that variable receives the exception
42instance, and the associated value is present as the exception
43instance's \code{args} attribute; this is a tuple even if the second
44argument to \code{raise} was not (then it is a singleton tuple).
45\stindex{raise}
Guido van Rossum5fdeeea1994-01-02 01:22:07 +000046
47User code can raise built-in exceptions. This can be used to test an
Guido van Rossumdf3dba01997-10-05 18:51:26 +000048exception handler or to report an error condition ``just like'' the
Guido van Rossum5fdeeea1994-01-02 01:22:07 +000049situation in which the interpreter raises the same exception; but
50beware that there is nothing to prevent user code from raising an
51inappropriate error.
52
Guido van Rossumdf3dba01997-10-05 18:51:26 +000053\renewcommand{\indexsubitem}{(built-in exception base class)}
54
55The following exceptions are only used as base classes for other
56exceptions. When string-based standard exceptions are used, they
57are tuples containing the directly derived classes.
58
59\begin{excdesc}{Exception}
60The root class for exceptions. All built-in exceptions are derived
61from this class. All user-defined exceptions should also be derived
62from this class, but this is not (yet) enforced. The \code{str()}
63function, when applied to an instance of this class (or most derived
64classes) returns the string value of the argument or arguments, or an
65empty string if no arguments were given to the constructor.
66\end{excdesc}
67
68\begin{excdesc}{StandardError}
69The base class for built-in exceptions. All built-in exceptions are
70derived from this class, which is itself derived from the root class
71\code{Exception}. For backward compatibility, when used as a
72sequence, this accesses the arguments given to the constructor.
73\end{excdesc}
74
75\begin{excdesc}{ArithmeticError}
76The base class for those built-in exceptions that are raised for
77various arithmetic errors: \code{OverflowError},
78\code{ZeroDivisionError}, \code{FloatingPointError}.
79\end{excdesc}
80
81\begin{excdesc}{LookupError}
82The base class for thise exceptions that are raised when a key or
83index used on a mapping or sequence is invalid: \code{IndexError},
84\code{KeyError}.
85\end{excdesc}
86
87\renewcommand{\indexsubitem}{(built-in exception base class)}
88
89The following exceptions are the exceptions that are actually raised.
90They are class objects, except when the \code{-X} option is used to
91revert back to string-based standard exceptions.
92
93\begin{excdesc}{AssertionError}
94Raised when an \code{assert} statement fails.
95\stindex{assert}
96\end{excdesc}
Guido van Rossum5fdeeea1994-01-02 01:22:07 +000097
98\begin{excdesc}{AttributeError}
99% xref to attribute reference?
100 Raised when an attribute reference or assignment fails. (When an
Guido van Rossum470be141995-03-17 16:07:09 +0000101 object does not support attribute references or attribute assignments
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000102 at all, \code{TypeError} is raised.)
103\end{excdesc}
104
105\begin{excdesc}{EOFError}
106% XXXJH xrefs here
107 Raised when one of the built-in functions (\code{input()} or
108 \code{raw_input()}) hits an end-of-file condition (\EOF{}) without
109 reading any data.
110% XXXJH xrefs here
111 (N.B.: the \code{read()} and \code{readline()} methods of file
112 objects return an empty string when they hit \EOF{}.) No associated value.
113\end{excdesc}
114
Guido van Rossumdf3dba01997-10-05 18:51:26 +0000115\begin{excdesc}{FloatingPointError}
116Raised when a floating point operation fails. This exception is
117always defined, but can only be raised when Python is configured with
118the \code{--with-fpectl} option, or the \code{WANT_SIGFPE_HANDLER}
119symbol is defined in the \file{config.h} file.
120\end{excdesc}
121
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000122\begin{excdesc}{IOError}
123% XXXJH xrefs here
124 Raised when an I/O operation (such as a \code{print} statement, the
125 built-in \code{open()} function or a method of a file object) fails
Guido van Rossumdf3dba01997-10-05 18:51:26 +0000126 for an I/O-related reason, e.g., ``file not found'' or ``disk full''.
127
128When class exceptions are used, and this exception is instantiated as
129\code{IOError(errno, strerror)}, the instance has two additional
130attributes \code{errno} and \code{strerror} set to the error code and
131the error message, respectively. These attributes default to
132\code{None}.
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000133\end{excdesc}
134
135\begin{excdesc}{ImportError}
136% XXXJH xref to import statement?
137 Raised when an \code{import} statement fails to find the module
138 definition or when a \code{from {\rm \ldots} import} fails to find a
139 name that is to be imported.
140\end{excdesc}
141
142\begin{excdesc}{IndexError}
143% XXXJH xref to sequences
144 Raised when a sequence subscript is out of range. (Slice indices are
145 silently truncated to fall in the allowed range; if an index is not a
146 plain integer, \code{TypeError} is raised.)
147\end{excdesc}
148
149\begin{excdesc}{KeyError}
150% XXXJH xref to mapping objects?
151 Raised when a mapping (dictionary) key is not found in the set of
152 existing keys.
153\end{excdesc}
154
155\begin{excdesc}{KeyboardInterrupt}
156 Raised when the user hits the interrupt key (normally
157 \kbd{Control-C} or
158\key{DEL}). During execution, a check for interrupts is made regularly.
159% XXXJH xrefs here
160 Interrupts typed when a built-in function \code{input()} or
161 \code{raw_input()}) is waiting for input also raise this exception. No
162 associated value.
163\end{excdesc}
164
165\begin{excdesc}{MemoryError}
166 Raised when an operation runs out of memory but the situation may
167 still be rescued (by deleting some objects). The associated value is
168 a string indicating what kind of (internal) operation ran out of memory.
169 Note that because of the underlying memory management architecture
170 (\C{}'s \code{malloc()} function), the interpreter may not always be able
171 to completely recover from this situation; it nevertheless raises an
172 exception so that a stack traceback can be printed, in case a run-away
173 program was the cause.
174\end{excdesc}
175
176\begin{excdesc}{NameError}
177 Raised when a local or global name is not found. This applies only
178 to unqualified names. The associated value is the name that could
179 not be found.
180\end{excdesc}
181
182\begin{excdesc}{OverflowError}
183% XXXJH reference to long's and/or int's?
184 Raised when the result of an arithmetic operation is too large to be
185 represented. This cannot occur for long integers (which would rather
186 raise \code{MemoryError} than give up). Because of the lack of
187 standardization of floating point exception handling in \C{}, most
188 floating point operations also aren't checked. For plain integers,
189 all operations that can overflow are checked except left shift, where
190 typical applications prefer to drop bits than raise an exception.
191\end{excdesc}
192
193\begin{excdesc}{RuntimeError}
194 Raised when an error is detected that doesn't fall in any of the
195 other categories. The associated value is a string indicating what
Guido van Rossumdf3dba01997-10-05 18:51:26 +0000196 precisely went wrong. (This exception is mostly a relic from a
197 previous version of the interpreter; it is not used very much any
198 more.)
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000199\end{excdesc}
200
201\begin{excdesc}{SyntaxError}
202% XXXJH xref to these functions?
203 Raised when the parser encounters a syntax error. This may occur in
204 an \code{import} statement, in an \code{exec} statement, in a call
205 to the built-in function \code{eval()} or \code{input()}, or
206 when reading the initial script or standard input (also
207 interactively).
Guido van Rossumdf3dba01997-10-05 18:51:26 +0000208
209When class exceptions are used, instances of this class have
210atttributes \code{filename}, \code{lineno}, \code{offset} and
211\code{text} for easier access to the details; for string exceptions,
212the associated value is usually a tuple of the form
213\code{(message, (filename, lineno, offset, text))}.
214For class exceptions, \code{str()} returns only the message.
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000215\end{excdesc}
216
217\begin{excdesc}{SystemError}
218 Raised when the interpreter finds an internal error, but the
219 situation does not look so serious to cause it to abandon all hope.
220 The associated value is a string indicating what went wrong (in
221 low-level terms).
222
223 You should report this to the author or maintainer of your Python
224 interpreter. Be sure to report the version string of the Python
225 interpreter (\code{sys.version}; it is also printed at the start of an
226 interactive Python session), the exact error message (the exception's
227 associated value) and if possible the source of the program that
228 triggered the error.
229\end{excdesc}
230
231\begin{excdesc}{SystemExit}
232% XXXJH xref to module sys?
233 This exception is raised by the \code{sys.exit()} function. When it
234 is not handled, the Python interpreter exits; no stack traceback is
235 printed. If the associated value is a plain integer, it specifies the
236 system exit status (passed to \C{}'s \code{exit()} function); if it is
237 \code{None}, the exit status is zero; if it has another type (such as
238 a string), the object's value is printed and the exit status is one.
Guido van Rossumdf3dba01997-10-05 18:51:26 +0000239
240When class exceptions are used, the instance has an attribute
241\code{code} which is set to the proposed exit status or error message
242(defaulting to \code{None}).
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000243
244 A call to \code{sys.exit} is translated into an exception so that
245 clean-up handlers (\code{finally} clauses of \code{try} statements)
246 can be executed, and so that a debugger can execute a script without
Guido van Rossumdf3dba01997-10-05 18:51:26 +0000247 running the risk of losing control. The \code{os._exit()} function
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000248 can be used if it is absolutely positively necessary to exit
249 immediately (e.g., after a \code{fork()} in the child process).
250\end{excdesc}
251
252\begin{excdesc}{TypeError}
253 Raised when a built-in operation or function is applied to an object
254 of inappropriate type. The associated value is a string giving
255 details about the type mismatch.
256\end{excdesc}
257
258\begin{excdesc}{ValueError}
259 Raised when a built-in operation or function receives an argument
260 that has the right type but an inappropriate value, and the
261 situation is not described by a more precise exception such as
262 \code{IndexError}.
263\end{excdesc}
264
265\begin{excdesc}{ZeroDivisionError}
266 Raised when the second argument of a division or modulo operation is
267 zero. The associated value is a string indicating the type of the
268 operands and the operation.
269\end{excdesc}