Georg Brandl | f5f2630 | 2008-08-08 06:50:56 +0000 | [diff] [blame] | 1 | .. _tut-errors: |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 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 | |
Guido van Rossum | 0616b79 | 2007-08-31 03:25:11 +0000 | [diff] [blame] | 20 | >>> while True print('Hello world') |
Terry Jan Reedy | 30eee4d | 2016-09-30 15:38:48 -0400 | [diff] [blame] | 21 | File "<stdin>", line 1 |
Guido van Rossum | 0616b79 | 2007-08-31 03:25:11 +0000 | [diff] [blame] | 22 | while True print('Hello world') |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 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 |
Georg Brandl | 6911e3c | 2007-09-04 07:15:32 +0000 | [diff] [blame] | 29 | example, the error is detected at the function :func:`print`, since a colon |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 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): |
Terry Jan Reedy | 30eee4d | 2016-09-30 15:38:48 -0400 | [diff] [blame] | 47 | File "<stdin>", line 1, in <module> |
Georg Brandl | 53bf15a | 2013-10-06 09:11:14 +0200 | [diff] [blame] | 48 | ZeroDivisionError: division by zero |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 49 | >>> 4 + spam*3 |
| 50 | Traceback (most recent call last): |
Terry Jan Reedy | 30eee4d | 2016-09-30 15:38:48 -0400 | [diff] [blame] | 51 | File "<stdin>", line 1, in <module> |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 52 | NameError: name 'spam' is not defined |
| 53 | >>> '2' + 2 |
| 54 | Traceback (most recent call last): |
Terry Jan Reedy | 30eee4d | 2016-09-30 15:38:48 -0400 | [diff] [blame] | 55 | File "<stdin>", line 1, in <module> |
Georg Brandl | 397ad86 | 2009-05-17 08:14:39 +0000 | [diff] [blame] | 56 | TypeError: Can't convert 'int' object to str implicitly |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 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: |
Guido van Rossum | 0616b79 | 2007-08-31 03:25:11 +0000 | [diff] [blame] | 93 | ... print("Oops! That was no valid number. Try again...") |
Georg Brandl | 48310cd | 2009-01-03 21:18:54 +0000 | [diff] [blame] | 94 | ... |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 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 |
Collin Winter | d2e44df | 2007-09-27 21:28:21 +0000 | [diff] [blame] | 118 | name multiple exceptions as a parenthesized tuple, for example:: |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 119 | |
Collin Winter | d2e44df | 2007-09-27 21:28:21 +0000 | [diff] [blame] | 120 | ... except (RuntimeError, TypeError, NameError): |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 121 | ... pass |
| 122 | |
Berker Peksag | cea632e | 2016-11-06 21:15:01 +0300 | [diff] [blame] | 123 | A class in an :keyword:`except` clause is compatible with an exception if it is |
| 124 | the same class or a base class thereof (but not the other way around --- an |
| 125 | except clause listing a derived class is not compatible with a base class). For |
| 126 | example, the following code will print B, C, D in that order:: |
| 127 | |
| 128 | class B(Exception): |
| 129 | pass |
| 130 | |
| 131 | class C(B): |
| 132 | pass |
| 133 | |
| 134 | class D(C): |
| 135 | pass |
| 136 | |
| 137 | for cls in [B, C, D]: |
| 138 | try: |
| 139 | raise cls() |
| 140 | except D: |
| 141 | print("D") |
| 142 | except C: |
| 143 | print("C") |
| 144 | except B: |
| 145 | print("B") |
| 146 | |
| 147 | Note that if the except clauses were reversed (with ``except B`` first), it |
| 148 | would have printed B, B, B --- the first matching except clause is triggered. |
| 149 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 150 | The last except clause may omit the exception name(s), to serve as a wildcard. |
| 151 | Use this with extreme caution, since it is easy to mask a real programming error |
| 152 | in this way! It can also be used to print an error message and then re-raise |
| 153 | the exception (allowing a caller to handle the exception as well):: |
| 154 | |
| 155 | import sys |
| 156 | |
| 157 | try: |
| 158 | f = open('myfile.txt') |
| 159 | s = f.readline() |
| 160 | i = int(s.strip()) |
Andrew Svetlov | 08af000 | 2014-04-01 01:13:30 +0300 | [diff] [blame] | 161 | except OSError as err: |
| 162 | print("OS error: {0}".format(err)) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 163 | except ValueError: |
Guido van Rossum | 0616b79 | 2007-08-31 03:25:11 +0000 | [diff] [blame] | 164 | print("Could not convert data to an integer.") |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 165 | except: |
Guido van Rossum | 0616b79 | 2007-08-31 03:25:11 +0000 | [diff] [blame] | 166 | print("Unexpected error:", sys.exc_info()[0]) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 167 | raise |
| 168 | |
| 169 | The :keyword:`try` ... :keyword:`except` statement has an optional *else |
| 170 | clause*, which, when present, must follow all except clauses. It is useful for |
| 171 | code that must be executed if the try clause does not raise an exception. For |
| 172 | example:: |
| 173 | |
| 174 | for arg in sys.argv[1:]: |
| 175 | try: |
| 176 | f = open(arg, 'r') |
Kushal Das | ecbca35 | 2016-11-16 21:13:43 +0530 | [diff] [blame] | 177 | except OSError: |
Guido van Rossum | 0616b79 | 2007-08-31 03:25:11 +0000 | [diff] [blame] | 178 | print('cannot open', arg) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 179 | else: |
Guido van Rossum | 0616b79 | 2007-08-31 03:25:11 +0000 | [diff] [blame] | 180 | print(arg, 'has', len(f.readlines()), 'lines') |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 181 | f.close() |
| 182 | |
| 183 | The use of the :keyword:`else` clause is better than adding additional code to |
| 184 | the :keyword:`try` clause because it avoids accidentally catching an exception |
| 185 | that wasn't raised by the code being protected by the :keyword:`try` ... |
| 186 | :keyword:`except` statement. |
| 187 | |
| 188 | When an exception occurs, it may have an associated value, also known as the |
| 189 | exception's *argument*. The presence and type of the argument depend on the |
| 190 | exception type. |
| 191 | |
Georg Brandl | f5f2630 | 2008-08-08 06:50:56 +0000 | [diff] [blame] | 192 | The except clause may specify a variable after the exception name. The |
| 193 | variable is bound to an exception instance with the arguments stored in |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 194 | ``instance.args``. For convenience, the exception instance defines |
Georg Brandl | f5f2630 | 2008-08-08 06:50:56 +0000 | [diff] [blame] | 195 | :meth:`__str__` so the arguments can be printed directly without having to |
| 196 | reference ``.args``. One may also instantiate an exception first before |
| 197 | raising it and add any attributes to it as desired. :: |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 198 | |
| 199 | >>> try: |
Serhiy Storchaka | dba9039 | 2016-05-10 12:01:23 +0300 | [diff] [blame] | 200 | ... raise Exception('spam', 'eggs') |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 201 | ... except Exception as inst: |
Serhiy Storchaka | dba9039 | 2016-05-10 12:01:23 +0300 | [diff] [blame] | 202 | ... print(type(inst)) # the exception instance |
| 203 | ... print(inst.args) # arguments stored in .args |
| 204 | ... print(inst) # __str__ allows args to be printed directly, |
| 205 | ... # but may be overridden in exception subclasses |
| 206 | ... x, y = inst.args # unpack args |
| 207 | ... print('x =', x) |
| 208 | ... print('y =', y) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 209 | ... |
Martin v. Löwis | 250ad61 | 2008-04-07 05:43:42 +0000 | [diff] [blame] | 210 | <class 'Exception'> |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 211 | ('spam', 'eggs') |
| 212 | ('spam', 'eggs') |
| 213 | x = spam |
| 214 | y = eggs |
| 215 | |
Georg Brandl | f5f2630 | 2008-08-08 06:50:56 +0000 | [diff] [blame] | 216 | If an exception has arguments, they are printed as the last part ('detail') of |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 217 | the message for unhandled exceptions. |
| 218 | |
| 219 | Exception handlers don't just handle exceptions if they occur immediately in the |
| 220 | try clause, but also if they occur inside functions that are called (even |
| 221 | indirectly) in the try clause. For example:: |
| 222 | |
| 223 | >>> def this_fails(): |
| 224 | ... x = 1/0 |
Georg Brandl | 48310cd | 2009-01-03 21:18:54 +0000 | [diff] [blame] | 225 | ... |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 226 | >>> try: |
| 227 | ... this_fails() |
Georg Brandl | f5f2630 | 2008-08-08 06:50:56 +0000 | [diff] [blame] | 228 | ... except ZeroDivisionError as err: |
| 229 | ... print('Handling run-time error:', err) |
Georg Brandl | 48310cd | 2009-01-03 21:18:54 +0000 | [diff] [blame] | 230 | ... |
Berker Peksag | cf79cdb | 2016-09-28 22:48:57 +0300 | [diff] [blame] | 231 | Handling run-time error: division by zero |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 232 | |
| 233 | |
| 234 | .. _tut-raising: |
| 235 | |
| 236 | Raising Exceptions |
| 237 | ================== |
| 238 | |
| 239 | The :keyword:`raise` statement allows the programmer to force a specified |
| 240 | exception to occur. For example:: |
| 241 | |
Collin Winter | 596d99a | 2007-09-10 00:31:50 +0000 | [diff] [blame] | 242 | >>> raise NameError('HiThere') |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 243 | Traceback (most recent call last): |
Terry Jan Reedy | 30eee4d | 2016-09-30 15:38:48 -0400 | [diff] [blame] | 244 | File "<stdin>", line 1, in <module> |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 245 | NameError: HiThere |
| 246 | |
Collin Winter | c7526f5 | 2007-09-10 00:36:57 +0000 | [diff] [blame] | 247 | The sole argument to :keyword:`raise` indicates the exception to be raised. |
| 248 | This must be either an exception instance or an exception class (a class that |
Berker Peksag | cea632e | 2016-11-06 21:15:01 +0300 | [diff] [blame] | 249 | derives from :class:`Exception`). If an exception class is passed, it will |
| 250 | be implicitly instantiated by calling its constructor with no arguments:: |
| 251 | |
| 252 | raise ValueError # shorthand for 'raise ValueError()' |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 253 | |
| 254 | If you need to determine whether an exception was raised but don't intend to |
| 255 | handle it, a simpler form of the :keyword:`raise` statement allows you to |
| 256 | re-raise the exception:: |
| 257 | |
| 258 | >>> try: |
Collin Winter | 596d99a | 2007-09-10 00:31:50 +0000 | [diff] [blame] | 259 | ... raise NameError('HiThere') |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 260 | ... except NameError: |
Guido van Rossum | 0616b79 | 2007-08-31 03:25:11 +0000 | [diff] [blame] | 261 | ... print('An exception flew by!') |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 262 | ... raise |
| 263 | ... |
| 264 | An exception flew by! |
| 265 | Traceback (most recent call last): |
Terry Jan Reedy | 30eee4d | 2016-09-30 15:38:48 -0400 | [diff] [blame] | 266 | File "<stdin>", line 2, in <module> |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 267 | NameError: HiThere |
| 268 | |
| 269 | |
| 270 | .. _tut-userexceptions: |
| 271 | |
| 272 | User-defined Exceptions |
| 273 | ======================= |
| 274 | |
Georg Brandl | ee8783d | 2009-09-16 16:00:31 +0000 | [diff] [blame] | 275 | Programs may name their own exceptions by creating a new exception class (see |
| 276 | :ref:`tut-classes` for more about Python classes). Exceptions should typically |
Raymond Hettinger | 7f65af3 | 2016-08-12 09:43:59 -0700 | [diff] [blame] | 277 | be derived from the :exc:`Exception` class, either directly or indirectly. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 278 | |
| 279 | Exception classes can be defined which do anything any other class can do, but |
| 280 | are usually kept simple, often only offering a number of attributes that allow |
| 281 | information about the error to be extracted by handlers for the exception. When |
| 282 | creating a module that can raise several distinct errors, a common practice is |
| 283 | to create a base class for exceptions defined by that module, and subclass that |
| 284 | to create specific exception classes for different error conditions:: |
| 285 | |
| 286 | class Error(Exception): |
| 287 | """Base class for exceptions in this module.""" |
| 288 | pass |
| 289 | |
| 290 | class InputError(Error): |
| 291 | """Exception raised for errors in the input. |
| 292 | |
| 293 | Attributes: |
| 294 | expression -- input expression in which the error occurred |
| 295 | message -- explanation of the error |
| 296 | """ |
| 297 | |
| 298 | def __init__(self, expression, message): |
| 299 | self.expression = expression |
| 300 | self.message = message |
| 301 | |
| 302 | class TransitionError(Error): |
| 303 | """Raised when an operation attempts a state transition that's not |
| 304 | allowed. |
| 305 | |
| 306 | Attributes: |
| 307 | previous -- state at beginning of transition |
| 308 | next -- attempted new state |
| 309 | message -- explanation of why the specific transition is not allowed |
| 310 | """ |
| 311 | |
| 312 | def __init__(self, previous, next, message): |
| 313 | self.previous = previous |
| 314 | self.next = next |
| 315 | self.message = message |
| 316 | |
| 317 | Most exceptions are defined with names that end in "Error," similar to the |
| 318 | naming of the standard exceptions. |
| 319 | |
| 320 | Many standard modules define their own exceptions to report errors that may |
| 321 | occur in functions they define. More information on classes is presented in |
| 322 | chapter :ref:`tut-classes`. |
| 323 | |
| 324 | |
| 325 | .. _tut-cleanup: |
| 326 | |
| 327 | Defining Clean-up Actions |
| 328 | ========================= |
| 329 | |
| 330 | The :keyword:`try` statement has another optional clause which is intended to |
| 331 | define clean-up actions that must be executed under all circumstances. For |
| 332 | example:: |
| 333 | |
| 334 | >>> try: |
| 335 | ... raise KeyboardInterrupt |
| 336 | ... finally: |
Guido van Rossum | 0616b79 | 2007-08-31 03:25:11 +0000 | [diff] [blame] | 337 | ... print('Goodbye, world!') |
Georg Brandl | 48310cd | 2009-01-03 21:18:54 +0000 | [diff] [blame] | 338 | ... |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 339 | Goodbye, world! |
| 340 | Traceback (most recent call last): |
Terry Jan Reedy | 30eee4d | 2016-09-30 15:38:48 -0400 | [diff] [blame] | 341 | File "<stdin>", line 2, in <module> |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 342 | KeyboardInterrupt |
| 343 | |
| 344 | A *finally clause* is always executed before leaving the :keyword:`try` |
| 345 | statement, whether an exception has occurred or not. When an exception has |
| 346 | occurred in the :keyword:`try` clause and has not been handled by an |
Martin Panter | 7462b649 | 2015-11-02 03:37:02 +0000 | [diff] [blame] | 347 | :keyword:`except` clause (or it has occurred in an :keyword:`except` or |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 348 | :keyword:`else` clause), it is re-raised after the :keyword:`finally` clause has |
| 349 | been executed. The :keyword:`finally` clause is also executed "on the way out" |
| 350 | when any other clause of the :keyword:`try` statement is left via a |
| 351 | :keyword:`break`, :keyword:`continue` or :keyword:`return` statement. A more |
Georg Brandl | e6bcc91 | 2008-05-12 18:05:20 +0000 | [diff] [blame] | 352 | complicated example:: |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 353 | |
| 354 | >>> def divide(x, y): |
| 355 | ... try: |
| 356 | ... result = x / y |
| 357 | ... except ZeroDivisionError: |
Guido van Rossum | 0616b79 | 2007-08-31 03:25:11 +0000 | [diff] [blame] | 358 | ... print("division by zero!") |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 359 | ... else: |
Guido van Rossum | 0616b79 | 2007-08-31 03:25:11 +0000 | [diff] [blame] | 360 | ... print("result is", result) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 361 | ... finally: |
Guido van Rossum | 0616b79 | 2007-08-31 03:25:11 +0000 | [diff] [blame] | 362 | ... print("executing finally clause") |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 363 | ... |
| 364 | >>> divide(2, 1) |
Georg Brandl | 397ad86 | 2009-05-17 08:14:39 +0000 | [diff] [blame] | 365 | result is 2.0 |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 366 | executing finally clause |
| 367 | >>> divide(2, 0) |
| 368 | division by zero! |
| 369 | executing finally clause |
| 370 | >>> divide("2", "1") |
| 371 | executing finally clause |
| 372 | Traceback (most recent call last): |
Terry Jan Reedy | 30eee4d | 2016-09-30 15:38:48 -0400 | [diff] [blame] | 373 | File "<stdin>", line 1, in <module> |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 374 | File "<stdin>", line 3, in divide |
| 375 | TypeError: unsupported operand type(s) for /: 'str' and 'str' |
| 376 | |
| 377 | As you can see, the :keyword:`finally` clause is executed in any event. The |
| 378 | :exc:`TypeError` raised by dividing two strings is not handled by the |
| 379 | :keyword:`except` clause and therefore re-raised after the :keyword:`finally` |
Benjamin Peterson | 5478b47 | 2008-09-17 22:25:09 +0000 | [diff] [blame] | 380 | clause has been executed. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 381 | |
| 382 | In real world applications, the :keyword:`finally` clause is useful for |
| 383 | releasing external resources (such as files or network connections), regardless |
| 384 | of whether the use of the resource was successful. |
| 385 | |
| 386 | |
| 387 | .. _tut-cleanup-with: |
| 388 | |
| 389 | Predefined Clean-up Actions |
| 390 | =========================== |
| 391 | |
| 392 | Some objects define standard clean-up actions to be undertaken when the object |
| 393 | is no longer needed, regardless of whether or not the operation using the object |
| 394 | succeeded or failed. Look at the following example, which tries to open a file |
| 395 | and print its contents to the screen. :: |
| 396 | |
| 397 | for line in open("myfile.txt"): |
Andrew Svetlov | 09974b4 | 2012-12-08 17:59:03 +0200 | [diff] [blame] | 398 | print(line, end="") |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 399 | |
| 400 | The problem with this code is that it leaves the file open for an indeterminate |
Georg Brandl | 48310cd | 2009-01-03 21:18:54 +0000 | [diff] [blame] | 401 | amount of time after this part of the code has finished executing. |
| 402 | This is not an issue in simple scripts, but can be a problem for larger |
| 403 | applications. The :keyword:`with` statement allows objects like files to be |
Guido van Rossum | 0616b79 | 2007-08-31 03:25:11 +0000 | [diff] [blame] | 404 | used in a way that ensures they are always cleaned up promptly and correctly. :: |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 405 | |
| 406 | with open("myfile.txt") as f: |
| 407 | for line in f: |
Andrew Svetlov | 09974b4 | 2012-12-08 17:59:03 +0200 | [diff] [blame] | 408 | print(line, end="") |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 409 | |
| 410 | After the statement is executed, the file *f* is always closed, even if a |
Guido van Rossum | 0616b79 | 2007-08-31 03:25:11 +0000 | [diff] [blame] | 411 | problem was encountered while processing the lines. Objects which, like files, |
| 412 | provide predefined clean-up actions will indicate this in their documentation. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 413 | |
| 414 | |