Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 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 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 88 | >>> while True: |
| 89 | ... try: |
Georg Brandl | e9af284 | 2007-08-17 05:54:09 +0000 | [diff] [blame] | 90 | ... x = int(input("Please enter a number: ")) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 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 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 | |
| 143 | The :keyword:`try` ... :keyword:`except` statement has an optional *else |
| 144 | clause*, which, when present, must follow all except clauses. It is useful for |
| 145 | code that must be executed if the try clause does not raise an exception. For |
| 146 | example:: |
| 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 | |
| 157 | The use of the :keyword:`else` clause is better than adding additional code to |
| 158 | the :keyword:`try` clause because it avoids accidentally catching an exception |
| 159 | that wasn't raised by the code being protected by the :keyword:`try` ... |
| 160 | :keyword:`except` statement. |
| 161 | |
| 162 | When an exception occurs, it may have an associated value, also known as the |
| 163 | exception's *argument*. The presence and type of the argument depend on the |
| 164 | exception type. |
| 165 | |
| 166 | The except clause may specify a variable after the exception name (or tuple). |
| 167 | The 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 |
| 170 | printed directly without having to reference ``.args``. |
| 171 | |
| 172 | But use of ``.args`` is discouraged. Instead, the preferred use is to pass a |
| 173 | single argument to an exception (which can be a tuple if multiple arguments are |
| 174 | needed) and have it bound to the ``message`` attribute. One may also |
| 175 | instantiate an exception first before raising it and add any attributes to it as |
| 176 | desired. :: |
| 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 | |
| 194 | If an exception has an argument, it is printed as the last part ('detail') of |
| 195 | the message for unhandled exceptions. |
| 196 | |
| 197 | Exception handlers don't just handle exceptions if they occur immediately in the |
| 198 | try clause, but also if they occur inside functions that are called (even |
| 199 | indirectly) 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 | |
| 214 | Raising Exceptions |
| 215 | ================== |
| 216 | |
| 217 | The :keyword:`raise` statement allows the programmer to force a specified |
| 218 | exception 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 | |
| 225 | The first argument to :keyword:`raise` names the exception to be raised. The |
| 226 | optional second argument specifies the exception's argument. Alternatively, the |
| 227 | above could be written as ``raise NameError('HiThere')``. Either form works |
| 228 | fine, but there seems to be a growing stylistic preference for the latter. |
| 229 | |
| 230 | If you need to determine whether an exception was raised but don't intend to |
| 231 | handle it, a simpler form of the :keyword:`raise` statement allows you to |
| 232 | re-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 | |
| 248 | User-defined Exceptions |
| 249 | ======================= |
| 250 | |
| 251 | Programs may name their own exceptions by creating a new exception class. |
| 252 | Exceptions should typically be derived from the :exc:`Exception` class, either |
| 253 | directly 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 | |
| 272 | In this example, the default :meth:`__init__` of :class:`Exception` has been |
| 273 | overridden. The new behavior simply creates the *value* attribute. This |
| 274 | replaces the default behavior of creating the *args* attribute. |
| 275 | |
| 276 | Exception classes can be defined which do anything any other class can do, but |
| 277 | are usually kept simple, often only offering a number of attributes that allow |
| 278 | information about the error to be extracted by handlers for the exception. When |
| 279 | creating a module that can raise several distinct errors, a common practice is |
| 280 | to create a base class for exceptions defined by that module, and subclass that |
| 281 | to 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 | |
| 314 | Most exceptions are defined with names that end in "Error," similar to the |
| 315 | naming of the standard exceptions. |
| 316 | |
| 317 | Many standard modules define their own exceptions to report errors that may |
| 318 | occur in functions they define. More information on classes is presented in |
| 319 | chapter :ref:`tut-classes`. |
| 320 | |
| 321 | |
| 322 | .. _tut-cleanup: |
| 323 | |
| 324 | Defining Clean-up Actions |
| 325 | ========================= |
| 326 | |
| 327 | The :keyword:`try` statement has another optional clause which is intended to |
| 328 | define clean-up actions that must be executed under all circumstances. For |
| 329 | example:: |
| 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 | |
| 341 | A *finally clause* is always executed before leaving the :keyword:`try` |
| 342 | statement, whether an exception has occurred or not. When an exception has |
| 343 | occurred 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 |
| 346 | been executed. The :keyword:`finally` clause is also executed "on the way out" |
| 347 | when any other clause of the :keyword:`try` statement is left via a |
| 348 | :keyword:`break`, :keyword:`continue` or :keyword:`return` statement. A more |
| 349 | complicated example (having :keyword:`except` and :keyword:`finally` clauses in |
| 350 | the 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 | |
| 375 | As 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` |
| 378 | clauses has been executed. |
| 379 | |
| 380 | In real world applications, the :keyword:`finally` clause is useful for |
| 381 | releasing external resources (such as files or network connections), regardless |
| 382 | of whether the use of the resource was successful. |
| 383 | |
| 384 | |
| 385 | .. _tut-cleanup-with: |
| 386 | |
| 387 | Predefined Clean-up Actions |
| 388 | =========================== |
| 389 | |
| 390 | Some objects define standard clean-up actions to be undertaken when the object |
| 391 | is no longer needed, regardless of whether or not the operation using the object |
| 392 | succeeded or failed. Look at the following example, which tries to open a file |
| 393 | and print its contents to the screen. :: |
| 394 | |
| 395 | for line in open("myfile.txt"): |
| 396 | print line |
| 397 | |
| 398 | The problem with this code is that it leaves the file open for an indeterminate |
| 399 | amount of time after the code has finished executing. This is not an issue in |
| 400 | simple 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 |
| 402 | ensures 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 | |
| 408 | After the statement is executed, the file *f* is always closed, even if a |
| 409 | problem was encountered while processing the lines. Other objects which provide |
| 410 | predefined clean-up actions will indicate this in their documentation. |
| 411 | |
| 412 | |