blob: 2f2719ad368ca6a357b7c8f04d73a383cc346aa7 [file] [log] [blame]
Georg Brandl116aa622007-08-15 14:28:22 +00001.. _tut-errors:
2
3*********************
4Errors and Exceptions
5*********************
6
7Until now error messages haven't been more than mentioned, but if you have tried
8out the examples you have probably seen some. There are (at least) two
9distinguishable kinds of errors: *syntax errors* and *exceptions*.
10
11
12.. _tut-syntaxerrors:
13
14Syntax Errors
15=============
16
17Syntax errors, also known as parsing errors, are perhaps the most common kind of
18complaint you get while you are still learning Python::
19
20 >>> while True print 'Hello world'
21 File "<stdin>", line 1, in ?
22 while True print 'Hello world'
23 ^
24 SyntaxError: invalid syntax
25
26The parser repeats the offending line and displays a little 'arrow' pointing at
27the earliest point in the line where the error was detected. The error is
28caused by (or at least detected at) the token *preceding* the arrow: in the
29example, the error is detected at the keyword :keyword:`print`, since a colon
30(``':'``) is missing before it. File name and line number are printed so you
31know where to look in case the input came from a script.
32
33
34.. _tut-exceptions:
35
36Exceptions
37==========
38
39Even if a statement or expression is syntactically correct, it may cause an
40error when an attempt is made to execute it. Errors detected during execution
41are called *exceptions* and are not unconditionally fatal: you will soon learn
42how to handle them in Python programs. Most exceptions are not handled by
43programs, however, and result in error messages as shown here::
44
45 >>> 10 * (1/0)
46 Traceback (most recent call last):
47 File "<stdin>", line 1, in ?
48 ZeroDivisionError: integer division or modulo by zero
49 >>> 4 + spam*3
50 Traceback (most recent call last):
51 File "<stdin>", line 1, in ?
52 NameError: name 'spam' is not defined
53 >>> '2' + 2
54 Traceback (most recent call last):
55 File "<stdin>", line 1, in ?
56 TypeError: cannot concatenate 'str' and 'int' objects
57
58The last line of the error message indicates what happened. Exceptions come in
59different types, and the type is printed as part of the message: the types in
60the example are :exc:`ZeroDivisionError`, :exc:`NameError` and :exc:`TypeError`.
61The string printed as the exception type is the name of the built-in exception
62that occurred. This is true for all built-in exceptions, but need not be true
63for user-defined exceptions (although it is a useful convention). Standard
64exception names are built-in identifiers (not reserved keywords).
65
66The rest of the line provides detail based on the type of exception and what
67caused it.
68
69The preceding part of the error message shows the context where the exception
70happened, in the form of a stack traceback. In general it contains a stack
71traceback listing source lines; however, it will not display lines read from
72standard input.
73
74:ref:`bltin-exceptions` lists the built-in exceptions and their meanings.
75
76
77.. _tut-handling:
78
79Handling Exceptions
80===================
81
82It is possible to write programs that handle selected exceptions. Look at the
83following example, which asks the user for input until a valid integer has been
84entered, but allows the user to interrupt the program (using :kbd:`Control-C` or
85whatever the operating system supports); note that a user-generated interruption
86is signalled by raising the :exc:`KeyboardInterrupt` exception. ::
87
Georg Brandl116aa622007-08-15 14:28:22 +000088 >>> while True:
89 ... try:
Georg Brandle9af2842007-08-17 05:54:09 +000090 ... x = int(input("Please enter a number: "))
Georg Brandl116aa622007-08-15 14:28:22 +000091 ... break
92 ... except ValueError:
93 ... print "Oops! That was no valid number. Try again..."
94 ...
95
96The :keyword:`try` statement works as follows.
97
98* First, the *try clause* (the statement(s) between the :keyword:`try` and
99 :keyword:`except` keywords) is executed.
100
101* If no exception occurs, the *except clause* is skipped and execution of the
102 :keyword:`try` statement is finished.
103
104* If an exception occurs during execution of the try clause, the rest of the
105 clause is skipped. Then if its type matches the exception named after the
106 :keyword:`except` keyword, the except clause is executed, and then execution
107 continues after the :keyword:`try` statement.
108
109* If an exception occurs which does not match the exception named in the except
110 clause, it is passed on to outer :keyword:`try` statements; if no handler is
111 found, it is an *unhandled exception* and execution stops with a message as
112 shown above.
113
114A :keyword:`try` statement may have more than one except clause, to specify
115handlers for different exceptions. At most one handler will be executed.
116Handlers only handle exceptions that occur in the corresponding try clause, not
117in other handlers of the same :keyword:`try` statement. An except clause may
118name multiple exceptions as a parenthesized tuple, for example::
119
120 ... except (RuntimeError, TypeError, NameError):
121 ... pass
122
123The last except clause may omit the exception name(s), to serve as a wildcard.
124Use this with extreme caution, since it is easy to mask a real programming error
125in this way! It can also be used to print an error message and then re-raise
126the exception (allowing a caller to handle the exception as well)::
127
128 import sys
129
130 try:
131 f = open('myfile.txt')
132 s = f.readline()
133 i = int(s.strip())
134 except IOError as e:
135 (errno, strerror) = e
136 print "I/O error(%s): %s" % (e.errno, e.strerror)
137 except ValueError:
138 print "Could not convert data to an integer."
139 except:
140 print "Unexpected error:", sys.exc_info()[0]
141 raise
142
143The :keyword:`try` ... :keyword:`except` statement has an optional *else
144clause*, which, when present, must follow all except clauses. It is useful for
145code that must be executed if the try clause does not raise an exception. For
146example::
147
148 for arg in sys.argv[1:]:
149 try:
150 f = open(arg, 'r')
151 except IOError:
152 print 'cannot open', arg
153 else:
154 print arg, 'has', len(f.readlines()), 'lines'
155 f.close()
156
157The use of the :keyword:`else` clause is better than adding additional code to
158the :keyword:`try` clause because it avoids accidentally catching an exception
159that wasn't raised by the code being protected by the :keyword:`try` ...
160:keyword:`except` statement.
161
162When an exception occurs, it may have an associated value, also known as the
163exception's *argument*. The presence and type of the argument depend on the
164exception type.
165
166The except clause may specify a variable after the exception name (or tuple).
167The variable is bound to an exception instance with the arguments stored in
168``instance.args``. For convenience, the exception instance defines
169:meth:`__getitem__` and :meth:`__str__` so the arguments can be accessed or
170printed directly without having to reference ``.args``.
171
172But use of ``.args`` is discouraged. Instead, the preferred use is to pass a
173single argument to an exception (which can be a tuple if multiple arguments are
174needed) and have it bound to the ``message`` attribute. One may also
175instantiate an exception first before raising it and add any attributes to it as
176desired. ::
177
178 >>> try:
179 ... raise Exception('spam', 'eggs')
180 ... except Exception as inst:
181 ... print type(inst) # the exception instance
182 ... print inst.args # arguments stored in .args
183 ... print inst # __str__ allows args to printed directly
184 ... x, y = inst # __getitem__ allows args to be unpacked directly
185 ... print 'x =', x
186 ... print 'y =', y
187 ...
188 <type 'Exception'>
189 ('spam', 'eggs')
190 ('spam', 'eggs')
191 x = spam
192 y = eggs
193
194If an exception has an argument, it is printed as the last part ('detail') of
195the message for unhandled exceptions.
196
197Exception handlers don't just handle exceptions if they occur immediately in the
198try clause, but also if they occur inside functions that are called (even
199indirectly) in the try clause. For example::
200
201 >>> def this_fails():
202 ... x = 1/0
203 ...
204 >>> try:
205 ... this_fails()
206 ... except ZeroDivisionError as detail:
207 ... print 'Handling run-time error:', detail
208 ...
209 Handling run-time error: integer division or modulo by zero
210
211
212.. _tut-raising:
213
214Raising Exceptions
215==================
216
217The :keyword:`raise` statement allows the programmer to force a specified
218exception to occur. For example::
219
220 >>> raise NameError, 'HiThere'
221 Traceback (most recent call last):
222 File "<stdin>", line 1, in ?
223 NameError: HiThere
224
225The first argument to :keyword:`raise` names the exception to be raised. The
226optional second argument specifies the exception's argument. Alternatively, the
227above could be written as ``raise NameError('HiThere')``. Either form works
228fine, but there seems to be a growing stylistic preference for the latter.
229
230If you need to determine whether an exception was raised but don't intend to
231handle it, a simpler form of the :keyword:`raise` statement allows you to
232re-raise the exception::
233
234 >>> try:
235 ... raise NameError, 'HiThere'
236 ... except NameError:
237 ... print 'An exception flew by!'
238 ... raise
239 ...
240 An exception flew by!
241 Traceback (most recent call last):
242 File "<stdin>", line 2, in ?
243 NameError: HiThere
244
245
246.. _tut-userexceptions:
247
248User-defined Exceptions
249=======================
250
251Programs may name their own exceptions by creating a new exception class.
252Exceptions should typically be derived from the :exc:`Exception` class, either
253directly or indirectly. For example::
254
255 >>> class MyError(Exception):
256 ... def __init__(self, value):
257 ... self.value = value
258 ... def __str__(self):
259 ... return repr(self.value)
260 ...
261 >>> try:
262 ... raise MyError(2*2)
263 ... except MyError as e:
264 ... print 'My exception occurred, value:', e.value
265 ...
266 My exception occurred, value: 4
267 >>> raise MyError, 'oops!'
268 Traceback (most recent call last):
269 File "<stdin>", line 1, in ?
270 __main__.MyError: 'oops!'
271
272In this example, the default :meth:`__init__` of :class:`Exception` has been
273overridden. The new behavior simply creates the *value* attribute. This
274replaces the default behavior of creating the *args* attribute.
275
276Exception classes can be defined which do anything any other class can do, but
277are usually kept simple, often only offering a number of attributes that allow
278information about the error to be extracted by handlers for the exception. When
279creating a module that can raise several distinct errors, a common practice is
280to create a base class for exceptions defined by that module, and subclass that
281to create specific exception classes for different error conditions::
282
283 class Error(Exception):
284 """Base class for exceptions in this module."""
285 pass
286
287 class InputError(Error):
288 """Exception raised for errors in the input.
289
290 Attributes:
291 expression -- input expression in which the error occurred
292 message -- explanation of the error
293 """
294
295 def __init__(self, expression, message):
296 self.expression = expression
297 self.message = message
298
299 class TransitionError(Error):
300 """Raised when an operation attempts a state transition that's not
301 allowed.
302
303 Attributes:
304 previous -- state at beginning of transition
305 next -- attempted new state
306 message -- explanation of why the specific transition is not allowed
307 """
308
309 def __init__(self, previous, next, message):
310 self.previous = previous
311 self.next = next
312 self.message = message
313
314Most exceptions are defined with names that end in "Error," similar to the
315naming of the standard exceptions.
316
317Many standard modules define their own exceptions to report errors that may
318occur in functions they define. More information on classes is presented in
319chapter :ref:`tut-classes`.
320
321
322.. _tut-cleanup:
323
324Defining Clean-up Actions
325=========================
326
327The :keyword:`try` statement has another optional clause which is intended to
328define clean-up actions that must be executed under all circumstances. For
329example::
330
331 >>> try:
332 ... raise KeyboardInterrupt
333 ... finally:
334 ... print 'Goodbye, world!'
335 ...
336 Goodbye, world!
337 Traceback (most recent call last):
338 File "<stdin>", line 2, in ?
339 KeyboardInterrupt
340
341A *finally clause* is always executed before leaving the :keyword:`try`
342statement, whether an exception has occurred or not. When an exception has
343occurred in the :keyword:`try` clause and has not been handled by an
344:keyword:`except` clause (or it has occurred in a :keyword:`except` or
345:keyword:`else` clause), it is re-raised after the :keyword:`finally` clause has
346been executed. The :keyword:`finally` clause is also executed "on the way out"
347when any other clause of the :keyword:`try` statement is left via a
348:keyword:`break`, :keyword:`continue` or :keyword:`return` statement. A more
349complicated example (having :keyword:`except` and :keyword:`finally` clauses in
350the same :keyword:`try` statement works as of Python 2.5)::
351
352 >>> def divide(x, y):
353 ... try:
354 ... result = x / y
355 ... except ZeroDivisionError:
356 ... print "division by zero!"
357 ... else:
358 ... print "result is", result
359 ... finally:
360 ... print "executing finally clause"
361 ...
362 >>> divide(2, 1)
363 result is 2
364 executing finally clause
365 >>> divide(2, 0)
366 division by zero!
367 executing finally clause
368 >>> divide("2", "1")
369 executing finally clause
370 Traceback (most recent call last):
371 File "<stdin>", line 1, in ?
372 File "<stdin>", line 3, in divide
373 TypeError: unsupported operand type(s) for /: 'str' and 'str'
374
375As you can see, the :keyword:`finally` clause is executed in any event. The
376:exc:`TypeError` raised by dividing two strings is not handled by the
377:keyword:`except` clause and therefore re-raised after the :keyword:`finally`
378clauses has been executed.
379
380In real world applications, the :keyword:`finally` clause is useful for
381releasing external resources (such as files or network connections), regardless
382of whether the use of the resource was successful.
383
384
385.. _tut-cleanup-with:
386
387Predefined Clean-up Actions
388===========================
389
390Some objects define standard clean-up actions to be undertaken when the object
391is no longer needed, regardless of whether or not the operation using the object
392succeeded or failed. Look at the following example, which tries to open a file
393and print its contents to the screen. ::
394
395 for line in open("myfile.txt"):
396 print line
397
398The problem with this code is that it leaves the file open for an indeterminate
399amount of time after the code has finished executing. This is not an issue in
400simple scripts, but can be a problem for larger applications. The
401:keyword:`with` statement allows objects like files to be used in a way that
402ensures they are always cleaned up promptly and correctly. ::
403
404 with open("myfile.txt") as f:
405 for line in f:
406 print line
407
408After the statement is executed, the file *f* is always closed, even if a
409problem was encountered while processing the lines. Other objects which provide
410predefined clean-up actions will indicate this in their documentation.
411
412