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