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
}
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
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
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
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
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.
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
}.
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
}.
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()
}.
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.
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.
120 \setindexsubitem{(built-in exception)
}
122 The following exceptions are the exceptions that are actually raised.
124 \begin{excdesc
}{AssertionError
}
126 Raised when an
\keyword{assert
} statement fails.
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.)
136 \begin{excdesc
}{EOFError
}
138 Raised when one of the built-in functions (
\function{input()
} or
139 \function{raw_input()
}) hits an end-of-file condition (
\EOF) without
142 (N.B.: the
\method{read()
} and
\method{readline()
} methods of file
143 objects return an empty string when they hit
\EOF.)
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.
154 \begin{excdesc
}{IOError
}
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
161 This class is derived from
\exception{EnvironmentError
}. See the
162 discussion above for more information on exception instance
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.
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.)
180 \begin{excdesc
}{KeyError
}
181 % XXXJH xref to mapping objects?
182 Raised when a mapping (dictionary) key is not found in the set of
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.
191 Interrupts typed when a built-in function
\function{input()
} or
192 \function{raw_input()
}) is waiting for input also raise this
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.
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 the name that could
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.
220 \begin{excdesc
}{OSError
}
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.
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.
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
}
246 \versionadded[Previously known as the
247 \exception{\refmodule{weakref
}.ReferenceError
}
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
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.
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
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
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
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
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
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.
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
}.
332 \begin{excdesc
}{UnicodeError
}
333 Raised when a Unicode-related encoding or decoding error occurs. It
334 is a subclass of
\exception{ValueError
}.
338 \begin{excdesc
}{ValueError
}
339 Raised when a built-in operation or function receives an argument
340 that has the right type but an inappropriate value, and the
341 situation is not described by a more precise exception such as
342 \exception{IndexError
}.
345 \begin{excdesc
}{WindowsError
}
346 Raised when a Windows-specific error occurs or when the error number
347 does not correspond to an
\cdata{errno
} value. The
348 \member{errno
} and
\member{strerror
} values are created from the
349 return values of the
\cfunction{GetLastError()
} and
350 \cfunction{FormatMessage()
} functions from the Windows Platform API.
351 This is a subclass of
\exception{OSError
}.
355 \begin{excdesc
}{ZeroDivisionError
}
356 Raised when the second argument of a division or modulo operation is
357 zero. The associated value is a string indicating the type of the
358 operands and the operation.
362 \setindexsubitem{(built-in warning)
}
364 The following exceptions are used as warning categories; see the
365 \module{warnings
} module for more information.
367 \begin{excdesc
}{Warning
}
368 Base class for warning categories.
371 \begin{excdesc
}{UserWarning
}
372 Base class for warnings generated by user code.
375 \begin{excdesc
}{DeprecationWarning
}
376 Base class for warnings about deprecated features.
379 \begin{excdesc
}{PendingDeprecationWarning
}
380 Base class for warnings about features which will be deprecated in the future.
383 \begin{excdesc
}{SyntaxWarning
}
384 Base class for warnings about dubious syntax
387 \begin{excdesc
}{RuntimeWarning
}
388 Base class for warnings about dubious runtime behavior.
391 The class hierarchy for built-in exceptions is:
398 | +-- KeyboardInterrupt
400 | +-- EnvironmentError
406 | | +-- NotImplementedError
408 | | +-- UnboundLocalError
411 | | +-- IndentationError
418 | +-- ArithmeticError
419 | | +-- OverflowError
420 | | +-- ZeroDivisionError
421 | | +-- FloatingPointError
429 +-- DeprecationWarning
430 +-- PendingDeprecationWarning