| 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 |
| 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 <module> |
| 48 |
ZeroDivisionError: integer division or modulo by zero |
| 49 |
>>> 4 + spam*3 |
| 50 |
Traceback (most recent call last): |
| 51 |
File "<stdin>", line 1, in <module> |
| 52 |
NameError: name 'spam' is not defined |
| 53 |
>>> '2' + 2 |
| 54 |
Traceback (most recent call last): |
| 55 |
File "<stdin>", line 1, in <module> |
| 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 |
Note that the parentheses around this tuple are required, because |
| 124 |
``except ValueError, e:`` was the syntax used for what is normally |
| 125 |
written as ``except ValueError as e:`` in modern Python (described |
| 126 |
below). The old syntax is still supported for backwards compatibility. |
| 127 |
This means ``except RuntimeError, TypeError`` is not equivalent to |
| 128 |
``except (RuntimeError, TypeError):`` but to ``except RuntimeError as |
| 129 |
TypeError:`` which is not what you want. |
| 130 |
|
| 131 |
The last except clause may omit the exception name(s), to serve as a wildcard. |
| 132 |
Use this with extreme caution, since it is easy to mask a real programming error |
| 133 |
in this way! It can also be used to print an error message and then re-raise |
| 134 |
the exception (allowing a caller to handle the exception as well):: |
| 135 |
|
| 136 |
import sys |
| 137 |
|
| 138 |
try: |
| 139 |
f = open('myfile.txt') |
| 140 |
s = f.readline() |
| 141 |
i = int(s.strip()) |
| 142 |
except IOError as e: |
| 143 |
print "I/O error({0}): {1}".format(e.errno, e.strerror) |
| 144 |
except ValueError: |
| 145 |
print "Could not convert data to an integer." |
| 146 |
except: |
| 147 |
print "Unexpected error:", sys.exc_info()[0] |
| 148 |
raise |
| 149 |
|
| 150 |
The :keyword:`try` ... :keyword:`except` statement has an optional *else |
| 151 |
clause*, which, when present, must follow all except clauses. It is useful for |
| 152 |
code that must be executed if the try clause does not raise an exception. For |
| 153 |
example:: |
| 154 |
|
| 155 |
for arg in sys.argv[1:]: |
| 156 |
try: |
| 157 |
f = open(arg, 'r') |
| 158 |
except IOError: |
| 159 |
print 'cannot open', arg |
| 160 |
else: |
| 161 |
print arg, 'has', len(f.readlines()), 'lines' |
| 162 |
f.close() |
| 163 |
|
| 164 |
The use of the :keyword:`else` clause is better than adding additional code to |
| 165 |
the :keyword:`try` clause because it avoids accidentally catching an exception |
| 166 |
that wasn't raised by the code being protected by the :keyword:`try` ... |
| 167 |
:keyword:`except` statement. |
| 168 |
|
| 169 |
When an exception occurs, it may have an associated value, also known as the |
| 170 |
exception's *argument*. The presence and type of the argument depend on the |
| 171 |
exception type. |
| 172 |
|
| 173 |
The except clause may specify a variable after the exception name (or tuple). |
| 174 |
The variable is bound to an exception instance with the arguments stored in |
| 175 |
``instance.args``. For convenience, the exception instance defines |
| 176 |
:meth:`__str__` so the arguments can be printed directly without having to |
| 177 |
reference ``.args``. |
| 178 |
|
| 179 |
One may also instantiate an exception first before raising it and add any |
| 180 |
attributes to it as desired. :: |
| 181 |
|
| 182 |
>>> try: |
| 183 |
... raise Exception('spam', 'eggs') |
| 184 |
... except Exception as inst: |
| 185 |
... print type(inst) # the exception instance |
| 186 |
... print inst.args # arguments stored in .args |
| 187 |
... print inst # __str__ allows args to be printed directly |
| 188 |
... x, y = inst.args |
| 189 |
... print 'x =', x |
| 190 |
... print 'y =', y |
| 191 |
... |
| 192 |
<type 'exceptions.Exception'> |
| 193 |
('spam', 'eggs') |
| 194 |
('spam', 'eggs') |
| 195 |
x = spam |
| 196 |
y = eggs |
| 197 |
|
| 198 |
If an exception has an argument, it is printed as the last part ('detail') of |
| 199 |
the message for unhandled exceptions. |
| 200 |
|
| 201 |
Exception handlers don't just handle exceptions if they occur immediately in the |
| 202 |
try clause, but also if they occur inside functions that are called (even |
| 203 |
indirectly) in the try clause. For example:: |
| 204 |
|
| 205 |
>>> def this_fails(): |
| 206 |
... x = 1/0 |
| 207 |
... |
| 208 |
>>> try: |
| 209 |
... this_fails() |
| 210 |
... except ZeroDivisionError as detail: |
| 211 |
... print 'Handling run-time error:', detail |
| 212 |
... |
| 213 |
Handling run-time error: integer division or modulo by zero |
| 214 |
|
| 215 |
|
| 216 |
.. _tut-raising: |
| 217 |
|
| 218 |
Raising Exceptions |
| 219 |
================== |
| 220 |
|
| 221 |
The :keyword:`raise` statement allows the programmer to force a specified |
| 222 |
exception to occur. For example:: |
| 223 |
|
| 224 |
>>> raise NameError('HiThere') |
| 225 |
Traceback (most recent call last): |
| 226 |
File "<stdin>", line 1, in <module> |
| 227 |
NameError: HiThere |
| 228 |
|
| 229 |
The sole argument to :keyword:`raise` indicates the exception to be raised. |
| 230 |
This must be either an exception instance or an exception class (a class that |
| 231 |
derives from :class:`Exception`). |
| 232 |
|
| 233 |
If you need to determine whether an exception was raised but don't intend to |
| 234 |
handle it, a simpler form of the :keyword:`raise` statement allows you to |
| 235 |
re-raise the exception:: |
| 236 |
|
| 237 |
>>> try: |
| 238 |
... raise NameError('HiThere') |
| 239 |
... except NameError: |
| 240 |
... print 'An exception flew by!' |
| 241 |
... raise |
| 242 |
... |
| 243 |
An exception flew by! |
| 244 |
Traceback (most recent call last): |
| 245 |
File "<stdin>", line 2, in <module> |
| 246 |
NameError: HiThere |
| 247 |
|
| 248 |
|
| 249 |
.. _tut-userexceptions: |
| 250 |
|
| 251 |
User-defined Exceptions |
| 252 |
======================= |
| 253 |
|
| 254 |
Programs may name their own exceptions by creating a new exception class (see |
| 255 |
:ref:`tut-classes` for more about Python classes). Exceptions should typically |
| 256 |
be derived from the :exc:`Exception` class, either directly or indirectly. For |
| 257 |
example:: |
| 258 |
|
| 259 |
>>> class MyError(Exception): |
| 260 |
... def __init__(self, value): |
| 261 |
... self.value = value |
| 262 |
... def __str__(self): |
| 263 |
... return repr(self.value) |
| 264 |
... |
| 265 |
>>> try: |
| 266 |
... raise MyError(2*2) |
| 267 |
... except MyError as e: |
| 268 |
... print 'My exception occurred, value:', e.value |
| 269 |
... |
| 270 |
My exception occurred, value: 4 |
| 271 |
>>> raise MyError('oops!') |
| 272 |
Traceback (most recent call last): |
| 273 |
File "<stdin>", line 1, in <module> |
| 274 |
__main__.MyError: 'oops!' |
| 275 |
|
| 276 |
In this example, the default :meth:`__init__` of :class:`Exception` has been |
| 277 |
overridden. The new behavior simply creates the *value* attribute. This |
| 278 |
replaces the default behavior of creating the *args* attribute. |
| 279 |
|
| 280 |
Exception classes can be defined which do anything any other class can do, but |
| 281 |
are usually kept simple, often only offering a number of attributes that allow |
| 282 |
information about the error to be extracted by handlers for the exception. When |
| 283 |
creating a module that can raise several distinct errors, a common practice is |
| 284 |
to create a base class for exceptions defined by that module, and subclass that |
| 285 |
to create specific exception classes for different error conditions:: |
| 286 |
|
| 287 |
class Error(Exception): |
| 288 |
"""Base class for exceptions in this module.""" |
| 289 |
pass |
| 290 |
|
| 291 |
class InputError(Error): |
| 292 |
"""Exception raised for errors in the input. |
| 293 |
|
| 294 |
Attributes: |
| 295 |
expr -- input expression in which the error occurred |
| 296 |
msg -- explanation of the error |
| 297 |
""" |
| 298 |
|
| 299 |
def __init__(self, expr, msg): |
| 300 |
self.expr = expr |
| 301 |
self.msg = msg |
| 302 |
|
| 303 |
class TransitionError(Error): |
| 304 |
"""Raised when an operation attempts a state transition that's not |
| 305 |
allowed. |
| 306 |
|
| 307 |
Attributes: |
| 308 |
prev -- state at beginning of transition |
| 309 |
next -- attempted new state |
| 310 |
msg -- explanation of why the specific transition is not allowed |
| 311 |
""" |
| 312 |
|
| 313 |
def __init__(self, prev, next, msg): |
| 314 |
self.prev = prev |
| 315 |
self.next = next |
| 316 |
self.msg = msg |
| 317 |
|
| 318 |
Most exceptions are defined with names that end in "Error", similar to the |
| 319 |
naming of the standard exceptions. |
| 320 |
|
| 321 |
Many standard modules define their own exceptions to report errors that may |
| 322 |
occur in functions they define. More information on classes is presented in |
| 323 |
chapter :ref:`tut-classes`. |
| 324 |
|
| 325 |
|
| 326 |
.. _tut-cleanup: |
| 327 |
|
| 328 |
Defining Clean-up Actions |
| 329 |
========================= |
| 330 |
|
| 331 |
The :keyword:`try` statement has another optional clause which is intended to |
| 332 |
define clean-up actions that must be executed under all circumstances. For |
| 333 |
example:: |
| 334 |
|
| 335 |
>>> try: |
| 336 |
... raise KeyboardInterrupt |
| 337 |
... finally: |
| 338 |
... print 'Goodbye, world!' |
| 339 |
... |
| 340 |
Goodbye, world! |
| 341 |
Traceback (most recent call last): |
| 342 |
File "<stdin>", line 2, in <module> |
| 343 |
KeyboardInterrupt |
| 344 |
|
| 345 |
A *finally clause* is always executed before leaving the :keyword:`try` |
| 346 |
statement, whether an exception has occurred or not. When an exception has |
| 347 |
occurred in the :keyword:`try` clause and has not been handled by an |
| 348 |
:keyword:`except` clause (or it has occurred in an :keyword:`except` or |
| 349 |
:keyword:`else` clause), it is re-raised after the :keyword:`finally` clause has |
| 350 |
been executed. The :keyword:`finally` clause is also executed "on the way out" |
| 351 |
when any other clause of the :keyword:`try` statement is left via a |
| 352 |
:keyword:`break`, :keyword:`continue` or :keyword:`return` statement. A more |
| 353 |
complicated example (having :keyword:`except` and :keyword:`finally` clauses in |
| 354 |
the same :keyword:`try` statement works as of Python 2.5):: |
| 355 |
|
| 356 |
>>> def divide(x, y): |
| 357 |
... try: |
| 358 |
... result = x / y |
| 359 |
... except ZeroDivisionError: |
| 360 |
... print "division by zero!" |
| 361 |
... else: |
| 362 |
... print "result is", result |
| 363 |
... finally: |
| 364 |
... print "executing finally clause" |
| 365 |
... |
| 366 |
>>> divide(2, 1) |
| 367 |
result is 2 |
| 368 |
executing finally clause |
| 369 |
>>> divide(2, 0) |
| 370 |
division by zero! |
| 371 |
executing finally clause |
| 372 |
>>> divide("2", "1") |
| 373 |
executing finally clause |
| 374 |
Traceback (most recent call last): |
| 375 |
File "<stdin>", line 1, in <module> |
| 376 |
File "<stdin>", line 3, in divide |
| 377 |
TypeError: unsupported operand type(s) for /: 'str' and 'str' |
| 378 |
|
| 379 |
As you can see, the :keyword:`finally` clause is executed in any event. The |
| 380 |
:exc:`TypeError` raised by dividing two strings is not handled by the |
| 381 |
:keyword:`except` clause and therefore re-raised after the :keyword:`finally` |
| 382 |
clause has been executed. |
| 383 |
|
| 384 |
In real world applications, the :keyword:`finally` clause is useful for |
| 385 |
releasing external resources (such as files or network connections), regardless |
| 386 |
of whether the use of the resource was successful. |
| 387 |
|
| 388 |
|
| 389 |
.. _tut-cleanup-with: |
| 390 |
|
| 391 |
Predefined Clean-up Actions |
| 392 |
=========================== |
| 393 |
|
| 394 |
Some objects define standard clean-up actions to be undertaken when the object |
| 395 |
is no longer needed, regardless of whether or not the operation using the object |
| 396 |
succeeded or failed. Look at the following example, which tries to open a file |
| 397 |
and print its contents to the screen. :: |
| 398 |
|
| 399 |
for line in open("myfile.txt"): |
| 400 |
print line, |
| 401 |
|
| 402 |
The problem with this code is that it leaves the file open for an indeterminate |
| 403 |
amount of time after the code has finished executing. This is not an issue in |
| 404 |
simple scripts, but can be a problem for larger applications. The |
| 405 |
:keyword:`with` statement allows objects like files to be used in a way that |
| 406 |
ensures they are always cleaned up promptly and correctly. :: |
| 407 |
|
| 408 |
with open("myfile.txt") as f: |
| 409 |
for line in f: |
| 410 |
print line, |
| 411 |
|
| 412 |
After the statement is executed, the file *f* is always closed, even if a |
| 413 |
problem was encountered while processing the lines. Other objects which provide |
| 414 |
predefined clean-up actions will indicate this in their documentation. |
| 415 |
|
| 416 |
|