-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy patherrors.html
1080 lines (1068 loc) · 37.3 KB
/
errors.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" lang="" xml:lang="">
<head>
<meta charset="utf-8" />
<meta name="generator" content="pandoc" />
<meta
name="viewport"
content="width=device-width, initial-scale=1.0, user-scalable=yes"
/>
<title>errors</title>
<style type="text/css">
code {
white-space: pre-wrap;
}
span.smallcaps {
font-variant: small-caps;
}
span.underline {
text-decoration: underline;
}
div.column {
display: inline-block;
vertical-align: top;
width: 50%;
}
</style>
</head>
<body>
<h3 id="navigation">Navigation</h3>
<ul>
<li>
<a href="https://docs.python.org/3/genindex.html" title="General Index"
>index</a
>
</li>
<li>
<a
href="https://docs.python.org/3/py-modindex.html"
title="Python Module Index"
>modules</a
>
|
</li>
<li><a href="classes.html" title="9. Classes">next</a> |</li>
<li>
<a href="inputoutput.html" title="7. Input and Output">previous</a> |
</li>
<li><img src="../_static/py.png" /></li>
<li><a href="https://www.python.org/">Python</a> »</li>
<li>
<a href="https://docs.python.org/3/index.html">3.9.5 Documentation</a> »
</li>
<li><a href="index.html">The Python Tutorial</a> »</li>
<li></li>
</ul>
<p><span id="tut-errors"></span></p>
<h1 id="errors-and-exceptions">
<span class="section-number">8. </span>Errors and Exceptions<a
href="#errors-and-exceptions"
class="headerlink"
title="Permalink to this headline"
>¶</a
>
</h1>
<p>
Until now error messages haven’t been more than mentioned, but if you have
tried out the examples you have probably seen some. There are (at least)
two distinguishable kinds of errors: <em>syntax errors</em> and
<em>exceptions</em>.
</p>
<p><span id="tut-syntaxerrors"></span></p>
<h2 id="syntax-errors">
<span class="section-number">8.1. </span>Syntax Errors<a
href="#syntax-errors"
class="headerlink"
title="Permalink to this headline"
>¶</a
>
</h2>
<p>
Syntax errors, also known as parsing errors, are perhaps the most common
kind of complaint you get while you are still learning Python:
</p>
<pre><code>>>> while True print('Hello world')
File "<stdin>", line 1
while True print('Hello world')
^
SyntaxError: invalid syntax</code></pre>
<p>
The parser repeats the offending line and displays a little ‘arrow’
pointing at the earliest point in the line where the error was detected.
The error is caused by (or at least detected at) the token
<em>preceding</em> the arrow: in the example, the error is detected at the
function
<a
href="https://docs.python.org/3/library/functions.html#print"
class="reference internal"
title="print"
><code class="sourceCode python"
><span class="bu">print</span>()</code
></a
>, since a colon (<code>':'</code>) is missing before it. File name and
line number are printed so you know where to look in case the input came
from a script.
</p>
<p><span id="tut-exceptions"></span></p>
<h2 id="exceptions">
<span class="section-number">8.2. </span>Exceptions<a
href="#exceptions"
class="headerlink"
title="Permalink to this headline"
>¶</a
>
</h2>
<p>
Even if a statement or expression is syntactically correct, it may cause
an error when an attempt is made to execute it. Errors detected during
execution are called <em>exceptions</em> and are not unconditionally
fatal: you will soon learn how to handle them in Python programs. Most
exceptions are not handled by programs, however, and result in error
messages as shown here:
</p>
<pre><code>>>> 10 * (1/0)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ZeroDivisionError: division by zero
>>> 4 + spam*3
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'spam' is not defined
>>> '2' + 2
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: Can't convert 'int' object to str implicitly</code></pre>
<p>
The last line of the error message indicates what happened. Exceptions
come in different types, and the type is printed as part of the message:
the types in the example are
<a
href="https://docs.python.org/3/library/exceptions.html#ZeroDivisionError"
class="reference internal"
title="ZeroDivisionError"
><code class="sourceCode python"
><span class="pp">ZeroDivisionError</span></code
></a
>,
<a
href="https://docs.python.org/3/library/exceptions.html#NameError"
class="reference internal"
title="NameError"
><code class="sourceCode python"
><span class="pp">NameError</span></code
></a
>
and
<a
href="https://docs.python.org/3/library/exceptions.html#TypeError"
class="reference internal"
title="TypeError"
><code class="sourceCode python"
><span class="pp">TypeError</span></code
></a
>. The string printed as the exception type is the name of the built-in
exception that occurred. This is true for all built-in exceptions, but
need not be true for user-defined exceptions (although it is a useful
convention). Standard exception names are built-in identifiers (not
reserved keywords).
</p>
<p>
The rest of the line provides detail based on the type of exception and
what caused it.
</p>
<p>
The preceding part of the error message shows the context where the
exception occurred, in the form of a stack traceback. In general it
contains a stack traceback listing source lines; however, it will not
display lines read from standard input.
</p>
<p>
<a
href="https://docs.python.org/3/library/exceptions.html#bltin-exceptions"
class="reference internal"
><span class="std std-ref">Built-in Exceptions</span></a
>
lists the built-in exceptions and their meanings.
</p>
<p><span id="tut-handling"></span></p>
<h2 id="handling-exceptions">
<span class="section-number">8.3. </span>Handling Exceptions<a
href="#handling-exceptions"
class="headerlink"
title="Permalink to this headline"
>¶</a
>
</h2>
<p>
It is possible to write programs that handle selected exceptions. Look at
the following example, which asks the user for input until a valid integer
has been entered, but allows the user to interrupt the program (using
Control-C or whatever the operating system supports); note that a
user-generated interruption is signalled by raising the
<a
href="https://docs.python.org/3/library/exceptions.html#KeyboardInterrupt"
class="reference internal"
title="KeyboardInterrupt"
><code class="sourceCode python"
><span class="pp">KeyboardInterrupt</span></code
></a
>
exception.
</p>
<pre><code>>>> while True:
... try:
... x = int(input("Please enter a number: "))
... break
... except ValueError:
... print("Oops! That was no valid number. Try again...")
...</code></pre>
<p>
The
<a
href="https://docs.python.org/3/reference/compound_stmts.html#try"
class="reference internal"
><code class="xref std std-keyword docutils literal notranslate"
>try</code
></a
>
statement works as follows.
</p>
<ul>
<li>
<p>
First, the <em>try clause</em> (the statement(s) between the
<a
href="https://docs.python.org/3/reference/compound_stmts.html#try"
class="reference internal"
><code class="xref std std-keyword docutils literal notranslate"
>try</code
></a
>
and
<a
href="https://docs.python.org/3/reference/compound_stmts.html#except"
class="reference internal"
><code class="xref std std-keyword docutils literal notranslate"
>except</code
></a
>
keywords) is executed.
</p>
</li>
<li>
<p>
If no exception occurs, the <em>except clause</em> is skipped and
execution of the
<a
href="https://docs.python.org/3/reference/compound_stmts.html#try"
class="reference internal"
><code class="xref std std-keyword docutils literal notranslate"
>try</code
></a
>
statement is finished.
</p>
</li>
<li>
<p>
If an exception occurs during execution of the try clause, the rest of
the clause is skipped. Then if its type matches the exception named
after the
<a
href="https://docs.python.org/3/reference/compound_stmts.html#except"
class="reference internal"
><code class="xref std std-keyword docutils literal notranslate"
>except</code
></a
>
keyword, the except clause is executed, and then execution continues
after the
<a
href="https://docs.python.org/3/reference/compound_stmts.html#try"
class="reference internal"
><code class="xref std std-keyword docutils literal notranslate"
>try</code
></a
>
statement.
</p>
</li>
<li>
<p>
If an exception occurs which does not match the exception named in the
except clause, it is passed on to outer
<a
href="https://docs.python.org/3/reference/compound_stmts.html#try"
class="reference internal"
><code class="xref std std-keyword docutils literal notranslate"
>try</code
></a
>
statements; if no handler is found, it is an
<em>unhandled exception</em> and execution stops with a message as
shown above.
</p>
</li>
</ul>
<p>
A
<a
href="https://docs.python.org/3/reference/compound_stmts.html#try"
class="reference internal"
><code class="xref std std-keyword docutils literal notranslate"
>try</code
></a
>
statement may have more than one except clause, to specify handlers for
different exceptions. At most one handler will be executed. Handlers only
handle exceptions that occur in the corresponding try clause, not in other
handlers of the same <code>try</code> statement. An except clause may name
multiple exceptions as a parenthesized tuple, for example:
</p>
<pre><code>... except (RuntimeError, TypeError, NameError):
... pass</code></pre>
<p>
A class in an
<a
href="https://docs.python.org/3/reference/compound_stmts.html#except"
class="reference internal"
><code class="xref std std-keyword docutils literal notranslate"
>except</code
></a
>
clause is compatible with an exception if it is the same class or a base
class thereof (but not the other way around — an except clause listing a
derived class is not compatible with a base class). For example, the
following code will print B, C, D in that order:
</p>
<pre><code>class B(Exception):
pass
class C(B):
pass
class D(C):
pass
for cls in [B, C, D]:
try:
raise cls()
except D:
print("D")
except C:
print("C")
except B:
print("B")</code></pre>
<p>
Note that if the except clauses were reversed (with
<code>except B</code> first), it would have printed B, B, B — the first
matching except clause is triggered.
</p>
<p>
The last except clause may omit the exception name(s), to serve as a
wildcard. Use this with extreme caution, since it is easy to mask a real
programming error in this way! It can also be used to print an error
message and then re-raise the exception (allowing a caller to handle the
exception as well):
</p>
<pre><code>import sys
try:
f = open('myfile.txt')
s = f.readline()
i = int(s.strip())
except OSError as err:
print("OS error: {0}".format(err))
except ValueError:
print("Could not convert data to an integer.")
except:
print("Unexpected error:", sys.exc_info()[0])
raise</code></pre>
<p>
The
<a
href="https://docs.python.org/3/reference/compound_stmts.html#try"
class="reference internal"
><code class="xref std std-keyword docutils literal notranslate"
>try</code
></a
>
…
<a
href="https://docs.python.org/3/reference/compound_stmts.html#except"
class="reference internal"
><code class="xref std std-keyword docutils literal notranslate"
>except</code
></a
>
statement has an optional <em>else clause</em>, which, when present, must
follow all except clauses. It is useful for code that must be executed if
the try clause does not raise an exception. For example:
</p>
<pre><code>for arg in sys.argv[1:]:
try:
f = open(arg, 'r')
except OSError:
print('cannot open', arg)
else:
print(arg, 'has', len(f.readlines()), 'lines')
f.close()</code></pre>
<p>
The use of the <code>else</code> clause is better than adding additional
code to the
<a
href="https://docs.python.org/3/reference/compound_stmts.html#try"
class="reference internal"
><code class="xref std std-keyword docutils literal notranslate"
>try</code
></a
>
clause because it avoids accidentally catching an exception that wasn’t
raised by the code being protected by the <code>try</code> …
<code>except</code> statement.
</p>
<p>
When an exception occurs, it may have an associated value, also known as
the exception’s <em>argument</em>. The presence and type of the argument
depend on the exception type.
</p>
<p>
The except clause may specify a variable after the exception name. The
variable is bound to an exception instance with the arguments stored in
<code>instance.args</code>. For convenience, the exception instance
defines
<a
href="https://docs.python.org/3/reference/datamodel.html#object.__str__"
class="reference internal"
title="object.__str__"
><code class="sourceCode python"><span class="bu">str</span>()</code></a
>
so the arguments can be printed directly without having to reference
<code>.args</code>. One may also instantiate an exception first before
raising it and add any attributes to it as desired.
</p>
<pre><code>>>> try:
... raise Exception('spam', 'eggs')
... except Exception as inst:
... print(type(inst)) # the exception instance
... print(inst.args) # arguments stored in .args
... print(inst) # __str__ allows args to be printed directly,
... # but may be overridden in exception subclasses
... x, y = inst.args # unpack args
... print('x =', x)
... print('y =', y)
...
<class 'Exception'>
('spam', 'eggs')
('spam', 'eggs')
x = spam
y = eggs</code></pre>
<p>
If an exception has arguments, they are printed as the last part
(‘detail’) of the message for unhandled exceptions.
</p>
<p>
Exception handlers don’t just handle exceptions if they occur immediately
in the try clause, but also if they occur inside functions that are called
(even indirectly) in the try clause. For example:
</p>
<pre><code>>>> def this_fails():
... x = 1/0
...
>>> try:
... this_fails()
... except ZeroDivisionError as err:
... print('Handling run-time error:', err)
...
Handling run-time error: division by zero</code></pre>
<p><span id="tut-raising"></span></p>
<h2 id="raising-exceptions">
<span class="section-number">8.4. </span>Raising Exceptions<a
href="#raising-exceptions"
class="headerlink"
title="Permalink to this headline"
>¶</a
>
</h2>
<p>
The
<a
href="https://docs.python.org/3/reference/simple_stmts.html#raise"
class="reference internal"
><code class="xref std std-keyword docutils literal notranslate"
>raise</code
></a
>
statement allows the programmer to force a specified exception to occur.
For example:
</p>
<pre><code>>>> raise NameError('HiThere')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: HiThere</code></pre>
<p>
The sole argument to
<a
href="https://docs.python.org/3/reference/simple_stmts.html#raise"
class="reference internal"
><code class="xref std std-keyword docutils literal notranslate"
>raise</code
></a
>
indicates the exception to be raised. This must be either an exception
instance or an exception class (a class that derives from
<a
href="https://docs.python.org/3/library/exceptions.html#Exception"
class="reference internal"
title="Exception"
><code class="sourceCode python"
><span class="pp">Exception</span></code
></a
>). If an exception class is passed, it will be implicitly instantiated by
calling its constructor with no arguments:
</p>
<pre><code>raise ValueError # shorthand for 'raise ValueError()'</code></pre>
<p>
If you need to determine whether an exception was raised but don’t intend
to handle it, a simpler form of the
<a
href="https://docs.python.org/3/reference/simple_stmts.html#raise"
class="reference internal"
><code class="xref std std-keyword docutils literal notranslate"
>raise</code
></a
>
statement allows you to re-raise the exception:
</p>
<pre><code>>>> try:
... raise NameError('HiThere')
... except NameError:
... print('An exception flew by!')
... raise
...
An exception flew by!
Traceback (most recent call last):
File "<stdin>", line 2, in <module>
NameError: HiThere</code></pre>
<p><span id="tut-exception-chaining"></span></p>
<h2 id="exception-chaining">
<span class="section-number">8.5. </span>Exception Chaining<a
href="#exception-chaining"
class="headerlink"
title="Permalink to this headline"
>¶</a
>
</h2>
<p>
The
<a
href="https://docs.python.org/3/reference/simple_stmts.html#raise"
class="reference internal"
><code class="xref std std-keyword docutils literal notranslate"
>raise</code
></a
>
statement allows an optional
<a
href="https://docs.python.org/3/reference/simple_stmts.html#raise"
class="reference internal"
><code class="xref std std-keyword docutils literal notranslate"
>from</code
></a
>
which enables chaining exceptions. For example:
</p>
<pre><code># exc must be exception instance or None.
raise RuntimeError from exc</code></pre>
<p>This can be useful when you are transforming exceptions. For example:</p>
<pre><code>>>> def func():
... raise IOError
...
>>> try:
... func()
... except IOError as exc:
... raise RuntimeError('Failed to open database') from exc
...
Traceback (most recent call last):
File "<stdin>", line 2, in <module>
File "<stdin>", line 2, in func
OSError
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "<stdin>", line 4, in <module>
RuntimeError: Failed to open database</code></pre>
<p>
Exception chaining happens automatically when an exception is raised
inside an
<a
href="https://docs.python.org/3/reference/compound_stmts.html#except"
class="reference internal"
><code class="xref std std-keyword docutils literal notranslate"
>except</code
></a
>
or
<a
href="https://docs.python.org/3/reference/compound_stmts.html#finally"
class="reference internal"
><code class="xref std std-keyword docutils literal notranslate"
>finally</code
></a
>
section. Exception chaining can be disabled by using
<code>from None</code> idiom:
</p>
<pre><code>>>> try:
... open('database.sqlite')
... except OSError:
... raise RuntimeError from None
...
Traceback (most recent call last):
File "<stdin>", line 4, in <module>
RuntimeError</code></pre>
<p>
For more information about chaining mechanics, see
<a
href="https://docs.python.org/3/library/exceptions.html#bltin-exceptions"
class="reference internal"
><span class="std std-ref">Built-in Exceptions</span></a
>.
</p>
<p><span id="tut-userexceptions"></span></p>
<h2 id="user-defined-exceptions">
<span class="section-number">8.6. </span>User-defined Exceptions<a
href="#user-defined-exceptions"
class="headerlink"
title="Permalink to this headline"
>¶</a
>
</h2>
<p>
Programs may name their own exceptions by creating a new exception class
(see
<a href="classes.html#tut-classes" class="reference internal"
><span class="std std-ref">Classes</span></a
>
for more about Python classes). Exceptions should typically be derived
from the
<a
href="https://docs.python.org/3/library/exceptions.html#Exception"
class="reference internal"
title="Exception"
><code class="sourceCode python"
><span class="pp">Exception</span></code
></a
>
class, either directly or indirectly.
</p>
<p>
Exception classes can be defined which do anything any other class can do,
but are usually kept simple, often only offering a number of attributes
that allow information about the error to be extracted by handlers for the
exception. When creating a module that can raise several distinct errors,
a common practice is to create a base class for exceptions defined by that
module, and subclass that to create specific exception classes for
different error conditions:
</p>
<pre><code>class Error(Exception):
"""Base class for exceptions in this module."""
pass
class InputError(Error):
"""Exception raised for errors in the input.
Attributes:
expression -- input expression in which the error occurred
message -- explanation of the error
"""
def __init__(self, expression, message):
self.expression = expression
self.message = message
class TransitionError(Error):
"""Raised when an operation attempts a state transition that's not
allowed.
Attributes:
previous -- state at beginning of transition
next -- attempted new state
message -- explanation of why the specific transition is not allowed
"""
def __init__(self, previous, next, message):
self.previous = previous
self.next = next
self.message = message</code></pre>
<p>
Most exceptions are defined with names that end in “Error”, similar to the
naming of the standard exceptions.
</p>
<p>
Many standard modules define their own exceptions to report errors that
may occur in functions they define. More information on classes is
presented in chapter
<a href="classes.html#tut-classes" class="reference internal"
><span class="std std-ref">Classes</span></a
>.
</p>
<p><span id="tut-cleanup"></span></p>
<h2 id="defining-clean-up-actions">
<span class="section-number">8.7. </span>Defining Clean-up Actions<a
href="#defining-clean-up-actions"
class="headerlink"
title="Permalink to this headline"
>¶</a
>
</h2>
<p>
The
<a
href="https://docs.python.org/3/reference/compound_stmts.html#try"
class="reference internal"
><code class="xref std std-keyword docutils literal notranslate"
>try</code
></a
>
statement has another optional clause which is intended to define clean-up
actions that must be executed under all circumstances. For example:
</p>
<pre><code>>>> try:
... raise KeyboardInterrupt
... finally:
... print('Goodbye, world!')
...
Goodbye, world!
KeyboardInterrupt
Traceback (most recent call last):
File "<stdin>", line 2, in <module></code></pre>
<p>
If a
<a
href="https://docs.python.org/3/reference/compound_stmts.html#finally"
class="reference internal"
><code class="xref std std-keyword docutils literal notranslate"
>finally</code
></a
>
clause is present, the <code>finally</code> clause will execute as the
last task before the
<a
href="https://docs.python.org/3/reference/compound_stmts.html#try"
class="reference internal"
><code class="xref std std-keyword docutils literal notranslate"
>try</code
></a
>
statement completes. The <code>finally</code> clause runs whether or not
the <code>try</code> statement produces an exception. The following points
discuss more complex cases when an exception occurs:
</p>
<ul>
<li>
<p>
If an exception occurs during execution of the
<code>try</code> clause, the exception may be handled by an
<a
href="https://docs.python.org/3/reference/compound_stmts.html#except"
class="reference internal"
><code class="xref std std-keyword docutils literal notranslate"
>except</code
></a
>
clause. If the exception is not handled by an
<code>except</code> clause, the exception is re-raised after the
<code>finally</code> clause has been executed.
</p>
</li>
<li>
<p>
An exception could occur during execution of an <code>except</code> or
<code>else</code> clause. Again, the exception is re-raised after the
<code>finally</code> clause has been executed.
</p>
</li>
<li>
<p>
If the <code>finally</code> clause executes a
<a
href="https://docs.python.org/3/reference/simple_stmts.html#break"
class="reference internal"
><code class="xref std std-keyword docutils literal notranslate"
>break</code
></a
>,
<a
href="https://docs.python.org/3/reference/simple_stmts.html#continue"
class="reference internal"
><code class="xref std std-keyword docutils literal notranslate"
>continue</code
></a
>
or
<a
href="https://docs.python.org/3/reference/simple_stmts.html#return"
class="reference internal"
><code class="xref std std-keyword docutils literal notranslate"
>return</code
></a
>
statement, exceptions are not re-raised.
</p>
</li>
<li>
<p>
If the <code>try</code> statement reaches a
<a
href="https://docs.python.org/3/reference/simple_stmts.html#break"
class="reference internal"
><code class="xref std std-keyword docutils literal notranslate"
>break</code
></a
>,
<a
href="https://docs.python.org/3/reference/simple_stmts.html#continue"
class="reference internal"
><code class="xref std std-keyword docutils literal notranslate"
>continue</code
></a
>
or
<a
href="https://docs.python.org/3/reference/simple_stmts.html#return"
class="reference internal"
><code class="xref std std-keyword docutils literal notranslate"
>return</code
></a
>
statement, the <code>finally</code> clause will execute just prior to
the <code>break</code>, <code>continue</code> or
<code>return</code> statement’s execution.
</p>
</li>
<li>
<p>
If a <code>finally</code> clause includes a
<code>return</code> statement, the returned value will be the one from
the <code>finally</code> clause’s <code>return</code> statement, not
the value from the <code>try</code> clause’s
<code>return</code> statement.
</p>
</li>
</ul>
<p>For example:</p>
<pre><code>>>> def bool_return():
... try:
... return True
... finally:
... return False
...
>>> bool_return()
False</code></pre>
<p>A more complicated example:</p>
<pre><code>>>> def divide(x, y):
... try:
... result = x / y
... except ZeroDivisionError:
... print("division by zero!")
... else:
... print("result is", result)
... finally:
... print("executing finally clause")
...
>>> divide(2, 1)
result is 2.0
executing finally clause
>>> divide(2, 0)
division by zero!
executing finally clause
>>> divide("2", "1")
executing finally clause
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 3, in divide
TypeError: unsupported operand type(s) for /: 'str' and 'str'</code></pre>
<p>
As you can see, the
<a
href="https://docs.python.org/3/reference/compound_stmts.html#finally"
class="reference internal"
><code class="xref std std-keyword docutils literal notranslate"
>finally</code
></a
>
clause is executed in any event. The
<a
href="https://docs.python.org/3/library/exceptions.html#TypeError"
class="reference internal"
title="TypeError"
><code class="sourceCode python"
><span class="pp">TypeError</span></code
></a
>
raised by dividing two strings is not handled by the
<a
href="https://docs.python.org/3/reference/compound_stmts.html#except"
class="reference internal"
><code class="xref std std-keyword docutils literal notranslate"
>except</code
></a
>
clause and therefore re-raised after the <code>finally</code> clause has
been executed.
</p>
<p>
In real world applications, the
<a
href="https://docs.python.org/3/reference/compound_stmts.html#finally"
class="reference internal"
><code class="xref std std-keyword docutils literal notranslate"
>finally</code
></a
>
clause is useful for releasing external resources (such as files or
network connections), regardless of whether the use of the resource was
successful.
</p>
<p><span id="tut-cleanup-with"></span></p>
<h2 id="predefined-clean-up-actions">
<span class="section-number">8.8. </span>Predefined Clean-up Actions<a
href="#predefined-clean-up-actions"
class="headerlink"
title="Permalink to this headline"
>¶</a
>
</h2>
<p>
Some objects define standard clean-up actions to be undertaken when the
object is no longer needed, regardless of whether or not the operation
using the object succeeded or failed. Look at the following example, which
tries to open a file and print its contents to the screen.
</p>
<pre><code>for line in open("myfile.txt"):
print(line, end="")</code></pre>
<p>
The problem with this code is that it leaves the file open for an
indeterminate amount of time after this part of the code has finished
executing. This is not an issue in simple scripts, but can be a problem
for larger applications. The
<a
href="https://docs.python.org/3/reference/compound_stmts.html#with"
class="reference internal"
><code class="xref std std-keyword docutils literal notranslate"
>with</code
></a
>
statement allows objects like files to be used in a way that ensures they
are always cleaned up promptly and correctly.
</p>
<pre><code>with open("myfile.txt") as f:
for line in f:
print(line, end="")</code></pre>
<p>
After the statement is executed, the file <em>f</em> is always closed,
even if a problem was encountered while processing the lines. Objects
which, like files, provide predefined clean-up actions will indicate this
in their documentation.
</p>
<h3 id="table-of-contents">
<a href="https://docs.python.org/3/contents.html">Table of Contents</a>
</h3>
<ul>
<li>
<a href="#" class="reference internal">8. Errors and Exceptions</a>
<ul>
<li>
<a href="#syntax-errors" class="reference internal"
>8.1. Syntax Errors</a
>
</li>
<li>
<a href="#exceptions" class="reference internal">8.2. Exceptions</a>
</li>
<li>
<a href="#handling-exceptions" class="reference internal"
>8.3. Handling Exceptions</a
>
</li>
<li>
<a href="#raising-exceptions" class="reference internal"
>8.4. Raising Exceptions</a
>
</li>
<li>
<a href="#exception-chaining" class="reference internal"
>8.5. Exception Chaining</a
>
</li>
<li>