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