blob: e78947cb684f0b1250300d04139ca72217647273 [file] [log] [blame]
Georg Brandlf5f26302008-08-08 06:50:56 +00001.. _tut-errors:
Georg Brandl116aa622007-08-15 14:28:22 +00002
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
Guido van Rossum0616b792007-08-31 03:25:11 +000020 >>> while True print('Hello world')
Georg Brandl116aa622007-08-15 14:28:22 +000021 File "<stdin>", line 1, in ?
Guido van Rossum0616b792007-08-31 03:25:11 +000022 while True print('Hello world')
Georg Brandl116aa622007-08-15 14:28:22 +000023 ^
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
Georg Brandl6911e3c2007-09-04 07:15:32 +000029example, the error is detected at the function :func:`print`, since a colon
Georg Brandl116aa622007-08-15 14:28:22 +000030(``':'``) 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 ?
Guido van Rossum0616b792007-08-31 03:25:11 +000048 ZeroDivisionError: int division or modulo by zero
Georg Brandl116aa622007-08-15 14:28:22 +000049 >>> 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 ?
Guido van Rossum0616b792007-08-31 03:25:11 +000056 TypeError: coercing to Unicode: need string or buffer, int found
Georg Brandl116aa622007-08-15 14:28:22 +000057
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:
Guido van Rossum0616b792007-08-31 03:25:11 +000093 ... print("Oops! That was no valid number. Try again...")
Georg Brandl48310cd2009-01-03 21:18:54 +000094 ...
Georg Brandl116aa622007-08-15 14:28:22 +000095
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
Collin Winterd2e44df2007-09-27 21:28:21 +0000118name multiple exceptions as a parenthesized tuple, for example::
Georg Brandl116aa622007-08-15 14:28:22 +0000119
Collin Winterd2e44df2007-09-27 21:28:21 +0000120 ... except (RuntimeError, TypeError, NameError):
Georg Brandl116aa622007-08-15 14:28:22 +0000121 ... 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())
Georg Brandlf5f26302008-08-08 06:50:56 +0000134 except IOError as err:
135 print("I/O error: {0}".format(err))
Georg Brandl116aa622007-08-15 14:28:22 +0000136 except ValueError:
Guido van Rossum0616b792007-08-31 03:25:11 +0000137 print("Could not convert data to an integer.")
Georg Brandl116aa622007-08-15 14:28:22 +0000138 except:
Guido van Rossum0616b792007-08-31 03:25:11 +0000139 print("Unexpected error:", sys.exc_info()[0])
Georg Brandl116aa622007-08-15 14:28:22 +0000140 raise
141
142The :keyword:`try` ... :keyword:`except` statement has an optional *else
143clause*, which, when present, must follow all except clauses. It is useful for
144code that must be executed if the try clause does not raise an exception. For
145example::
146
147 for arg in sys.argv[1:]:
148 try:
149 f = open(arg, 'r')
150 except IOError:
Guido van Rossum0616b792007-08-31 03:25:11 +0000151 print('cannot open', arg)
Georg Brandl116aa622007-08-15 14:28:22 +0000152 else:
Guido van Rossum0616b792007-08-31 03:25:11 +0000153 print(arg, 'has', len(f.readlines()), 'lines')
Georg Brandl116aa622007-08-15 14:28:22 +0000154 f.close()
155
156The use of the :keyword:`else` clause is better than adding additional code to
157the :keyword:`try` clause because it avoids accidentally catching an exception
158that wasn't raised by the code being protected by the :keyword:`try` ...
159:keyword:`except` statement.
160
161When an exception occurs, it may have an associated value, also known as the
162exception's *argument*. The presence and type of the argument depend on the
163exception type.
164
Georg Brandlf5f26302008-08-08 06:50:56 +0000165The except clause may specify a variable after the exception name. The
166variable is bound to an exception instance with the arguments stored in
Georg Brandl116aa622007-08-15 14:28:22 +0000167``instance.args``. For convenience, the exception instance defines
Georg Brandlf5f26302008-08-08 06:50:56 +0000168:meth:`__str__` so the arguments can be printed directly without having to
169reference ``.args``. One may also instantiate an exception first before
170raising it and add any attributes to it as desired. ::
Georg Brandl116aa622007-08-15 14:28:22 +0000171
172 >>> try:
173 ... raise Exception('spam', 'eggs')
174 ... except Exception as inst:
Guido van Rossum0616b792007-08-31 03:25:11 +0000175 ... print(type(inst)) # the exception instance
176 ... print(inst.args) # arguments stored in .args
Georg Brandlf5f26302008-08-08 06:50:56 +0000177 ... print(inst) # __str__ allows args to be printed directly,
178 ... # but may be overridden in exception subclasses
179 ... x, y = inst.args # unpack args
Georg Brandl6911e3c2007-09-04 07:15:32 +0000180 ... print('x =', x)
181 ... print('y =', y)
Georg Brandl116aa622007-08-15 14:28:22 +0000182 ...
Martin v. Löwis250ad612008-04-07 05:43:42 +0000183 <class 'Exception'>
Georg Brandl116aa622007-08-15 14:28:22 +0000184 ('spam', 'eggs')
185 ('spam', 'eggs')
186 x = spam
187 y = eggs
188
Georg Brandlf5f26302008-08-08 06:50:56 +0000189If an exception has arguments, they are printed as the last part ('detail') of
Georg Brandl116aa622007-08-15 14:28:22 +0000190the message for unhandled exceptions.
191
192Exception handlers don't just handle exceptions if they occur immediately in the
193try clause, but also if they occur inside functions that are called (even
194indirectly) in the try clause. For example::
195
196 >>> def this_fails():
197 ... x = 1/0
Georg Brandl48310cd2009-01-03 21:18:54 +0000198 ...
Georg Brandl116aa622007-08-15 14:28:22 +0000199 >>> try:
200 ... this_fails()
Georg Brandlf5f26302008-08-08 06:50:56 +0000201 ... except ZeroDivisionError as err:
202 ... print('Handling run-time error:', err)
Georg Brandl48310cd2009-01-03 21:18:54 +0000203 ...
Georg Brandlf5f26302008-08-08 06:50:56 +0000204 Handling run-time error: int division or modulo by zero
Georg Brandl116aa622007-08-15 14:28:22 +0000205
206
207.. _tut-raising:
208
209Raising Exceptions
210==================
211
212The :keyword:`raise` statement allows the programmer to force a specified
213exception to occur. For example::
214
Collin Winter596d99a2007-09-10 00:31:50 +0000215 >>> raise NameError('HiThere')
Georg Brandl116aa622007-08-15 14:28:22 +0000216 Traceback (most recent call last):
217 File "<stdin>", line 1, in ?
218 NameError: HiThere
219
Collin Winterc7526f52007-09-10 00:36:57 +0000220The sole argument to :keyword:`raise` indicates the exception to be raised.
221This must be either an exception instance or an exception class (a class that
222derives from :class:`Exception`).
Georg Brandl116aa622007-08-15 14:28:22 +0000223
224If you need to determine whether an exception was raised but don't intend to
225handle it, a simpler form of the :keyword:`raise` statement allows you to
226re-raise the exception::
227
228 >>> try:
Collin Winter596d99a2007-09-10 00:31:50 +0000229 ... raise NameError('HiThere')
Georg Brandl116aa622007-08-15 14:28:22 +0000230 ... except NameError:
Guido van Rossum0616b792007-08-31 03:25:11 +0000231 ... print('An exception flew by!')
Georg Brandl116aa622007-08-15 14:28:22 +0000232 ... raise
233 ...
234 An exception flew by!
235 Traceback (most recent call last):
236 File "<stdin>", line 2, in ?
237 NameError: HiThere
238
239
240.. _tut-userexceptions:
241
242User-defined Exceptions
243=======================
244
245Programs may name their own exceptions by creating a new exception class.
246Exceptions should typically be derived from the :exc:`Exception` class, either
247directly or indirectly. For example::
248
249 >>> class MyError(Exception):
250 ... def __init__(self, value):
251 ... self.value = value
252 ... def __str__(self):
253 ... return repr(self.value)
Georg Brandl48310cd2009-01-03 21:18:54 +0000254 ...
Georg Brandl116aa622007-08-15 14:28:22 +0000255 >>> try:
256 ... raise MyError(2*2)
257 ... except MyError as e:
Georg Brandl6911e3c2007-09-04 07:15:32 +0000258 ... print('My exception occurred, value:', e.value)
Georg Brandl48310cd2009-01-03 21:18:54 +0000259 ...
Georg Brandl116aa622007-08-15 14:28:22 +0000260 My exception occurred, value: 4
Collin Winter58721bc2007-09-10 00:39:52 +0000261 >>> raise MyError('oops!')
Georg Brandl116aa622007-08-15 14:28:22 +0000262 Traceback (most recent call last):
263 File "<stdin>", line 1, in ?
264 __main__.MyError: 'oops!'
265
266In this example, the default :meth:`__init__` of :class:`Exception` has been
267overridden. The new behavior simply creates the *value* attribute. This
268replaces the default behavior of creating the *args* attribute.
269
270Exception classes can be defined which do anything any other class can do, but
271are usually kept simple, often only offering a number of attributes that allow
272information about the error to be extracted by handlers for the exception. When
273creating a module that can raise several distinct errors, a common practice is
274to create a base class for exceptions defined by that module, and subclass that
275to create specific exception classes for different error conditions::
276
277 class Error(Exception):
278 """Base class for exceptions in this module."""
279 pass
280
281 class InputError(Error):
282 """Exception raised for errors in the input.
283
284 Attributes:
285 expression -- input expression in which the error occurred
286 message -- explanation of the error
287 """
288
289 def __init__(self, expression, message):
290 self.expression = expression
291 self.message = message
292
293 class TransitionError(Error):
294 """Raised when an operation attempts a state transition that's not
295 allowed.
296
297 Attributes:
298 previous -- state at beginning of transition
299 next -- attempted new state
300 message -- explanation of why the specific transition is not allowed
301 """
302
303 def __init__(self, previous, next, message):
304 self.previous = previous
305 self.next = next
306 self.message = message
307
308Most exceptions are defined with names that end in "Error," similar to the
309naming of the standard exceptions.
310
311Many standard modules define their own exceptions to report errors that may
312occur in functions they define. More information on classes is presented in
313chapter :ref:`tut-classes`.
314
315
316.. _tut-cleanup:
317
318Defining Clean-up Actions
319=========================
320
321The :keyword:`try` statement has another optional clause which is intended to
322define clean-up actions that must be executed under all circumstances. For
323example::
324
325 >>> try:
326 ... raise KeyboardInterrupt
327 ... finally:
Guido van Rossum0616b792007-08-31 03:25:11 +0000328 ... print('Goodbye, world!')
Georg Brandl48310cd2009-01-03 21:18:54 +0000329 ...
Georg Brandl116aa622007-08-15 14:28:22 +0000330 Goodbye, world!
331 Traceback (most recent call last):
332 File "<stdin>", line 2, in ?
333 KeyboardInterrupt
334
335A *finally clause* is always executed before leaving the :keyword:`try`
336statement, whether an exception has occurred or not. When an exception has
337occurred in the :keyword:`try` clause and has not been handled by an
338:keyword:`except` clause (or it has occurred in a :keyword:`except` or
339:keyword:`else` clause), it is re-raised after the :keyword:`finally` clause has
340been executed. The :keyword:`finally` clause is also executed "on the way out"
341when any other clause of the :keyword:`try` statement is left via a
342:keyword:`break`, :keyword:`continue` or :keyword:`return` statement. A more
Georg Brandle6bcc912008-05-12 18:05:20 +0000343complicated example::
Georg Brandl116aa622007-08-15 14:28:22 +0000344
345 >>> def divide(x, y):
346 ... try:
347 ... result = x / y
348 ... except ZeroDivisionError:
Guido van Rossum0616b792007-08-31 03:25:11 +0000349 ... print("division by zero!")
Georg Brandl116aa622007-08-15 14:28:22 +0000350 ... else:
Guido van Rossum0616b792007-08-31 03:25:11 +0000351 ... print("result is", result)
Georg Brandl116aa622007-08-15 14:28:22 +0000352 ... finally:
Guido van Rossum0616b792007-08-31 03:25:11 +0000353 ... print("executing finally clause")
Georg Brandl116aa622007-08-15 14:28:22 +0000354 ...
355 >>> divide(2, 1)
356 result is 2
357 executing finally clause
358 >>> divide(2, 0)
359 division by zero!
360 executing finally clause
361 >>> divide("2", "1")
362 executing finally clause
363 Traceback (most recent call last):
364 File "<stdin>", line 1, in ?
365 File "<stdin>", line 3, in divide
366 TypeError: unsupported operand type(s) for /: 'str' and 'str'
367
368As you can see, the :keyword:`finally` clause is executed in any event. The
369:exc:`TypeError` raised by dividing two strings is not handled by the
370:keyword:`except` clause and therefore re-raised after the :keyword:`finally`
Benjamin Peterson5478b472008-09-17 22:25:09 +0000371clause has been executed.
Georg Brandl116aa622007-08-15 14:28:22 +0000372
373In real world applications, the :keyword:`finally` clause is useful for
374releasing external resources (such as files or network connections), regardless
375of whether the use of the resource was successful.
376
377
378.. _tut-cleanup-with:
379
380Predefined Clean-up Actions
381===========================
382
383Some objects define standard clean-up actions to be undertaken when the object
384is no longer needed, regardless of whether or not the operation using the object
385succeeded or failed. Look at the following example, which tries to open a file
386and print its contents to the screen. ::
387
388 for line in open("myfile.txt"):
Guido van Rossum0616b792007-08-31 03:25:11 +0000389 print(line)
Georg Brandl116aa622007-08-15 14:28:22 +0000390
391The problem with this code is that it leaves the file open for an indeterminate
Georg Brandl48310cd2009-01-03 21:18:54 +0000392amount of time after this part of the code has finished executing.
393This is not an issue in simple scripts, but can be a problem for larger
394applications. The :keyword:`with` statement allows objects like files to be
Guido van Rossum0616b792007-08-31 03:25:11 +0000395used in a way that ensures they are always cleaned up promptly and correctly. ::
Georg Brandl116aa622007-08-15 14:28:22 +0000396
397 with open("myfile.txt") as f:
398 for line in f:
Guido van Rossum0616b792007-08-31 03:25:11 +0000399 print(line)
Georg Brandl116aa622007-08-15 14:28:22 +0000400
401After the statement is executed, the file *f* is always closed, even if a
Guido van Rossum0616b792007-08-31 03:25:11 +0000402problem was encountered while processing the lines. Objects which, like files,
403provide predefined clean-up actions will indicate this in their documentation.
Georg Brandl116aa622007-08-15 14:28:22 +0000404
405