Uh oh!
There was an error while loading. Please reload this page.
- Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy path6_exceptions.html
More file actions
Latest commit
845 lines (806 loc) · 91.9 KB
/
Copy path6_exceptions.html
File metadata and controls
845 lines (806 loc) · 91.9 KB
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
<!DOCTYPE html>
<htmllang="en" data-content_root="./">
<head>
<metacharset="utf-8" />
<metaname="viewport" content="width=device-width, initial-scale=1.0" /><metaname="viewport" content="width=device-width, initial-scale=1" />
<title>6. Errors and exceptions — Object-oriented Programming documentation</title>
<linkrel="stylesheet" type="text/css" href="_static/pygments.css?v=03e43079" />
<linkrel="stylesheet" type="text/css" href="_static/fenics.css?v=8c7d05f9" />
<linkrel="stylesheet" type="text/css" href="_static/proof.css" />
<linkrel="stylesheet" type="text/css" href="_static/graphviz.css?v=fd3f3429" />
<scriptsrc="_static/documentation_options.js?v=5929fcd5"></script>
<scriptsrc="_static/doctools.js?v=9a2dae69"></script>
<scriptsrc="_static/sphinx_highlight.js?v=dc90522c"></script>
<scriptsrc="_static/proof.js"></script>
<scriptasync="async" src="https://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML"></script>
<linkrel="index" title="Index" href="genindex.html" />
<linkrel="search" title="Search" href="search.html" />
<linkrel="next" title="7. Inheritance and composition" href="7_inheritance.html" />
<linkrel="prev" title="5. Abstract data types" href="5_abstract_data_types.html" />
<!--[if lte IE 6]>
<link rel="stylesheet" href="_static/ie6.css" type="text/css" media="screen" charset="utf-8" />
<![endif]-->
<!-- Global site tag (gtag.js) - Google Analytics -->
<scriptasyncsrc="https://www.googletagmanager.com/gtag/js?id=G-0EFVH5C4DC"></script>
<script>
window.dataLayer=window.dataLayer||[];
functiongtag(){dataLayer.push(arguments);}
gtag('js',newDate());
gtag('config','G-0EFVH5C4DC');
</script>
<linkrel="stylesheet" href="_static/featured.css">
<linkrel="shortcut icon" href="_static/icon.ico" />
</head><body>
<divclass="wrapper">
<ahref="index.html"><imgsrc="_static/banner.png" width="900px" alt="FInAT Project Banner" /></a>
<divid="access">
<divclass="menu">
<ul>
<liclass="page_item"><ahref="index.html" title="Book">Book</a></li>
<liclass="page_item"><ahref="videos.html" title="Videos">Videos</a></li>
<liclass="page_item"><ahref="exercises.html"
title="Exercises">Exercises</a></li>
<liclass="page_item"><ahref="installation.html" title="Installation">Installation</a></li>
</ul>
</div><!-- .menu -->
</div><!-- #access -->
</div><!-- #wrapper -->
<divclass="document">
<divclass="documentwrapper">
<divclass="bodywrapper">
<divclass="body" role="main">
<sectionid="errors-and-exceptions">
<spanid="id1"></span><h1><spanclass="section-number">6. </span>Errors and exceptions<aclass="headerlink" href="#errors-and-exceptions" title="Link to this heading">¶</a></h1>
<details>
<summary>
Video: errors and exceptions.</summary><divclass="video_wrapper" style="">
<iframeallowfullscreen="true" src="https://player.vimeo.com/video/509280820" style="border: 0; height: 345px; width: 560px">
</iframe></div><p>Imperial students can also <aclass="reference external" href="https://imperial.cloud.panopto.eu/Panopto/Pages/Viewer.aspx?id=9c437655-106e-47d2-85d4-ae1c00db1ca7">watch this video on Panopto</a>.</p>
</details><p>It is a sight familiar to every programmer: instead of producing the
desired result, the screen is filled with seemingly unintelligible
garbage because an error has occurred. Producing errors is an
unavoidable part of programming, so learning to understand and correct
them is an essential part of learning to program.</p>
<sectionid="what-is-an-error">
<h2><spanclass="section-number">6.1. </span>What is an error?<aclass="headerlink" href="#what-is-an-error" title="Link to this heading">¶</a></h2>
<p>In mathematics, we are used to the idea that an expression might not
be defined. For example, in the absence of further information,
<spanclass="math notranslate nohighlight">\(0/0\)</span> does not have a well-defined value. Similarly, the string
of symbols <spanclass="math notranslate nohighlight">\(3 \times \%\)</span> does not have a mathematical
meaning. It is likewise very easy to create statements or expressions
in a programming language which either don’t have a well-defined
meaning, or which just don’t amount to a meaningful statement within
the rules of the language. A mathematician confronting an undefined
mathematical expression can do little else than throw up their hands
and ask the author what they meant. The <aclass="reference internal" href="2_programs_in_files.html#term-Python-interpreter"><spanclass="xref std std-term">Python interpreter</span></a>, upon
encountering code which has no defined meaning, responds similarly;
though rather than raising its non-existent hands, it raises an
<aclass="reference internal" href="#term-exception"><spanclass="xref std std-term">exception</span></a>. It is then up to the programmer to divine what to do next.</p>
<p>Let’s take a look at what Python does in response to a simple
error:</p>
<divclass="highlight-ipython3 notranslate"><divclass="highlight"><pre><span></span><spanclass="gp">In [3]: </span><spanclass="mf">0.</span><spanclass="o">/</span><spanclass="mf">0.</span>
<spanclass="gt">--------------------------------------------------------------------------</span>
<spanclass="ne">ZeroDivisionError</span><spanclass="g g-Whitespace"></span>Traceback (most recent call last)
<spanclass="n">Cell</span><spanclass="n">In</span><spanclass="p">[</span><spanclass="mi">3</span><spanclass="p">],</span><spanclass="n">line</span><spanclass="mi">1</span>
<spanclass="ne">----> </span><spanclass="mi">1</span><spanclass="mf">0.</span><spanclass="o">/</span><spanclass="mf">0.</span>
<spanclass="ne">ZeroDivisionError</span>: float division by zero
</pre></div>
</div>
<p>An important rule in interpreting Python errors, the reasons for which we will
return to, is to always read the error message from the bottom up. In
this case, the last line contains the name of the exception which has
been raised, <aclass="reference external" href="https://docs.python.org/3/library/exceptions.html#ZeroDivisionError" title="(in Python v3.14)"><codeclass="xref py py-obj docutils literal notranslate"><spanclass="pre">ZeroDivisionError</span></code></a>, followed by a colon, followed by
a descriptive string providing more information about what has gone
wrong. In this case, that more or less says the same as the exception
name, but that won’t be the case for all exceptions. The four lines
above the exception are called a <aclass="reference internal" href="#term-traceback"><spanclass="xref std std-term">traceback</span></a>. We’ll return to
interpreting tracebacks presently. In this case the error is easy to interpret
and understand: the code divided the <aclass="reference external" href="https://docs.python.org/3/library/functions.html#float" title="(in Python v3.14)"><codeclass="xref py py-class docutils literal notranslate"><spanclass="pre">float</span></code></a> value <codeclass="xref py py-obj docutils literal notranslate"><spanclass="pre">0.</span></code> by another zero,
and this does not have a well-defined result in Python’s arithmetic system.</p>
<sectionid="syntax-errors">
<h3><spanclass="section-number">6.1.1. </span>Syntax errors<aclass="headerlink" href="#syntax-errors" title="Link to this heading">¶</a></h3>
<p>Now consider the case of an expression that doesn’t make mathematical sense:</p>
<divclass="highlight-ipython3 notranslate"><divclass="highlight"><pre><span></span><spanclass="gp">In [5]: </span><spanclass="mi">3</span><spanclass="o">*</span><spanclass="o">%</span>
<spanclass="go">Cell In [5], line 1</span>
<spanclass="go"> 3 * %</span>
<spanclass="go"> ^</span>
<spanclass="go">SyntaxError: invalid syntax</span>
</pre></div>
</div>
<p>This creates a syntax error, signified by a <aclass="reference external" href="https://docs.python.org/3/library/exceptions.html#SyntaxError" title="(in Python v3.14)"><codeclass="xref py py-obj docutils literal notranslate"><spanclass="pre">SyntaxError</span></code></a> exception. In
programming languages, as with human languages, the syntax is the set of rules
which defines which expressions are well-formed. Notice that the earlier lines
of a syntax error appear somewhat different to those of the previous exception.
Almost all exceptions occur because the <aclass="reference internal" href="2_programs_in_files.html#term-Python-interpreter"><spanclass="xref std std-term">Python interpreter</span></a> attempts to
evaluate a statement or expression and encounters a problem. Syntax errors are
a special case: when a syntax error occurs, the interpreter can’t even get as
far as attempting to evaluate because the sequence of characters it has been
asked to execute do not make sense in Python. This time, the error message
shows the precise point in the line at which the Python interpreter found a
problem. This is indicated by the caret symbol (<codeclass="xref py py-obj docutils literal notranslate"><spanclass="pre">^</span></code>). In this case, the reason
that the expression doesn’t make any sense is that the modulo operator (<codeclass="xref py py-obj docutils literal notranslate"><spanclass="pre">%</span></code>) is
not a permissible second operand to multiplication (<codeclass="xref py py-obj docutils literal notranslate"><spanclass="pre">*</span></code>), so the Python
interpreter places the caret under the modulo operator.</p>
<p>Even though the Python interpreter will highlight the point at which
the syntax doesn’t make sense, this might not quite actually be the
point at which you made the mistake. In particular, failing to finish
a line of code will often result in the interpreter assuming that the
expression continues on the next line of program text, resulting in
the syntax error appearing to be one line later than it really
occurs. Consider the following code:</p>
<divclass="highlight-python3 notranslate"><divclass="highlight"><pre><span></span><spanclass="n">a</span><spanclass="o">=</span><spanclass="p">(</span><spanclass="mi">1</span><spanclass="p">,</span><spanclass="mi">2</span>
<spanclass="nb">print</span><spanclass="p">(</span><spanclass="n">a</span><spanclass="p">)</span>
</pre></div>
</div>
<p>The error here is a missing closing bracket on the first line, however
the error message which the <aclass="reference internal" href="2_programs_in_files.html#term-Python-interpreter"><spanclass="xref std std-term">Python interpreter</span></a> prints when this code is run is:</p>
<divclass="highlight-python3 notranslate"><divclass="highlight"><pre><span></span><spanclass="n">File</span><spanclass="s2">"syntax_error.py"</span><spanclass="p">,</span><spanclass="n">line</span><spanclass="mi">2</span>
<spanclass="nb">print</span><spanclass="p">(</span><spanclass="n">a</span><spanclass="p">)</span>
<spanclass="o">^</span>
<spanclass="ne">SyntaxError</span><spanclass="p">:</span><spanclass="n">invalid</span><spanclass="n">syntax</span>
</pre></div>
</div>
<p>To understand why Python reports the error on the line following the
actual problem, we need to understand that the missing closing bracket
was not by itself an error. The user could, after all, validly
continue the <aclass="reference external" href="https://docs.python.org/3/library/stdtypes.html#tuple" title="(in Python v3.14)"><codeclass="xref py py-class docutils literal notranslate"><spanclass="pre">tuple</span></code></a> constructor on the next line. For example,
the following code would be completely valid:</p>
<divclass="highlight-python3 notranslate"><divclass="highlight"><pre><span></span><spanclass="n">a</span><spanclass="o">=</span><spanclass="p">(</span><spanclass="mi">1</span><spanclass="p">,</span><spanclass="mi">2</span>
<spanclass="p">)</span>
<spanclass="nb">print</span><spanclass="p">(</span><spanclass="n">a</span><spanclass="p">)</span>
</pre></div>
</div>
<p>This means that the <aclass="reference internal" href="2_programs_in_files.html#term-Python-interpreter"><spanclass="xref std std-term">Python interpreter</span></a> can only know that something is
wrong when it sees <aclass="reference external" href="https://docs.python.org/3/library/functions.html#print" title="(in Python v3.14)"><codeclass="xref py py-obj docutils literal notranslate"><spanclass="pre">print</span></code></a>, because <aclass="reference external" href="https://docs.python.org/3/library/functions.html#print" title="(in Python v3.14)"><codeclass="xref py py-obj docutils literal notranslate"><spanclass="pre">print</span></code></a> cannot follow <codeclass="xref py py-obj docutils literal notranslate"><spanclass="pre">2</span></code> in a
tuple constructor. The interpreter, therefore, reports that the <aclass="reference external" href="https://docs.python.org/3/library/functions.html#print" title="(in Python v3.14)"><codeclass="xref py py-obj docutils literal notranslate"><spanclass="pre">print</span></code></a>
is a syntax error.</p>
<divclass="admonition hint">
<pclass="admonition-title">Hint</p>
<p>If the Python interpreter reports a syntax error at the start of a
line, always check to see if the actual error is on the previous
line.</p>
</div>
</section>
</section>
<sectionid="exceptions">
<h2><spanclass="section-number">6.2. </span>Exceptions<aclass="headerlink" href="#exceptions" title="Link to this heading">¶</a></h2>
<p>Aside from syntax errors, which are handled directly by the
interpreter, errors occur when Python code is executed and something
goes wrong. In these cases the Python code in which the problem is
encountered must signal this to the interpreter. It does this using a
special kind of object called an <aclass="reference internal" href="#term-exception"><spanclass="xref std std-term">exception</span></a>. When an exception
occurs, the interpreter stops executing the usual sequence of Python
commands. Unless the programmer has taken special measures, to which
we will return in <aclass="reference internal" href="#handling-exceptions"><spanclass="std std-numref">Section 6.5</span></a>, the execution will
cease and an error message will result.</p>
<p>Because there are many things that can go wrong, Python has many types
of exception built in. For example, if we attempt to access the number
2 position in a tuple with only two entries, then an
<aclass="reference external" href="https://docs.python.org/3/library/exceptions.html#IndexError" title="(in Python v3.14)"><codeclass="xref py py-class docutils literal notranslate"><spanclass="pre">IndexError</span></code></a> exception occurs:</p>
<divclass="highlight-ipython3 notranslate"><divclass="highlight"><pre><span></span><spanclass="gp">In [1]: </span><spanclass="p">(</span><spanclass="mi">0</span><spanclass="p">,</span><spanclass="mi">1</span><spanclass="p">)[</span><spanclass="mi">2</span><spanclass="p">]</span>
<spanclass="gt">--------------------------------------------------------------------------</span>
<spanclass="ne">IndexError</span><spanclass="g g-Whitespace"></span>Traceback (most recent call last)
<spanclass="n">Cell</span><spanclass="n">In</span><spanclass="p">[</span><spanclass="mi">1</span><spanclass="p">],</span><spanclass="n">line</span><spanclass="mi">1</span>
<spanclass="ne">----> </span><spanclass="mi">1</span><spanclass="p">(</span><spanclass="mi">0</span><spanclass="p">,</span><spanclass="mi">1</span><spanclass="p">)[</span><spanclass="mi">2</span><spanclass="p">]</span>
<spanclass="ne">IndexError</span>: tuple index out of range
</pre></div>
</div>
<p>The exception type provides some indication as
to what has gone wrong, and there is usually also an error message and
sometimes more data to help diagnose the problem. The <aclass="reference external" href="https://docs.python.org/3/library/exceptions.html" title="(in Python v3.14)"><spanclass="xref std std-doc">full list
of built-in exceptions</span></a> is available in the
Python documentation. Python developers can define their own
exceptions so there are many more defined in third-party packages. We will
turn to the subject of defining new exception classes in
<aclass="reference internal" href="7_inheritance.html#defining-exceptions"><spanclass="std std-numref">Section 7.4</span></a>.</p>
</section>
<sectionid="tracebacks-finding-errors">
<h2><spanclass="section-number">6.3. </span>Tracebacks: finding errors<aclass="headerlink" href="#tracebacks-finding-errors" title="Link to this heading">¶</a></h2>
<details>
<summary>
Video: tracebacks.</summary><divclass="video_wrapper" style="">
<iframeallowfullscreen="true" src="https://player.vimeo.com/video/509280880" style="border: 0; height: 345px; width: 560px">
</iframe></div><p>Imperial students can also <aclass="reference external" href="https://imperial.cloud.panopto.eu/Panopto/Pages/Viewer.aspx?id=55886da2-963f-43c3-9dc2-ae1c00db2513">watch this video on Panopto</a>.</p>
</details><p>The errors we have looked at so far have all been located in the top
level of code either typed directly into iPython or executed in a
script. However, what happens if an error occurs in a function call or
even several functions down? Consider the following code, which uses
the <codeclass="xref py py-class docutils literal notranslate"><spanclass="pre">Polynomial</span></code> class from
<aclass="reference internal" href="3_objects.html#objects"><spanclass="std std-numref">Chapter 3</span></a>:</p>
<divclass="highlight-ipython3 notranslate"><divclass="highlight"><pre><span></span><spanclass="gp">In [1]: </span><spanclass="kn">from</span><spanclass="w"></span><spanclass="nn">example_code.polynomial</span><spanclass="w"></span><spanclass="kn">import</span><spanclass="n">Polynomial</span>
<spanclass="gp">In [2]: </span><spanclass="n">p</span><spanclass="o">=</span><spanclass="n">Polynomial</span><spanclass="p">((</span><spanclass="s2">"a"</span><spanclass="p">,</span><spanclass="s2">"b"</span><spanclass="p">))</span>
<spanclass="gp">In [3]: </span><spanclass="nb">print</span><spanclass="p">(</span><spanclass="n">p</span><spanclass="p">)</span>
<spanclass="go">bx + a</span>
</pre></div>
</div>
<p>Perhaps surprisingly, it turns out that we are able to define a polynomial
whose coefficients are letters, and we can even print the resulting object.
However, if we attempt to add this polynomial to the number 1, we are in
trouble:</p>
<divclass="highlight-ipython3 notranslate"><divclass="highlight"><pre><span></span><spanclass="gp">In [4]: </span><spanclass="nb">print</span><spanclass="p">(</span><spanclass="mi">1</span><spanclass="o">+</span><spanclass="n">p</span><spanclass="p">)</span>
<spanclass="gt">--------------------------------------------------------------------------</span>
<spanclass="ne">TypeError</span><spanclass="g g-Whitespace"></span>Traceback (most recent call last)
<spanclass="n">Cell</span><spanclass="n">In</span><spanclass="p">[</span><spanclass="mi">4</span><spanclass="p">],</span><spanclass="n">line</span><spanclass="mi">1</span>
<spanclass="ne">----> </span><spanclass="mi">1</span><spanclass="nb">print</span><spanclass="p">(</span><spanclass="mi">1</span><spanclass="o">+</span><spanclass="n">p</span><spanclass="p">)</span>
<spanclass="nn">File ~/docs/principles_of_programming/object-oriented-programming/example_code/polynomial.py:59,</span> in <spanclass="ni">Polynomial.__radd__</span><spanclass="nt">(self, other)</span>
<spanclass="g g-Whitespace"></span><spanclass="mi">58</span><spanclass="k">def</span><spanclass="w"></span><spanclass="fm">__radd__</span><spanclass="p">(</span><spanclass="bp">self</span><spanclass="p">,</span><spanclass="n">other</span><spanclass="p">):</span>
<spanclass="ne">---> </span><spanclass="mi">59</span><spanclass="k">return</span><spanclass="bp">self</span><spanclass="o">+</span><spanclass="n">other</span>
<spanclass="nn">File ~/docs/principles_of_programming/object-oriented-programming/example_code/polynomial.py:38,</span> in <spanclass="ni">Polynomial.__add__</span><spanclass="nt">(self, other)</span>
<spanclass="g g-Whitespace"></span><spanclass="mi">36</span><spanclass="k">def</span><spanclass="w"></span><spanclass="fm">__add__</span><spanclass="p">(</span><spanclass="bp">self</span><spanclass="p">,</span><spanclass="n">other</span><spanclass="p">):</span>
<spanclass="g g-Whitespace"></span><spanclass="mi">37</span><spanclass="k">if</span><spanclass="nb">isinstance</span><spanclass="p">(</span><spanclass="n">other</span><spanclass="p">,</span><spanclass="n">Number</span><spanclass="p">):</span>
<spanclass="ne">---> </span><spanclass="mi">38</span><spanclass="k">return</span><spanclass="n">Polynomial</span><spanclass="p">((</span><spanclass="bp">self</span><spanclass="o">.</span><spanclass="n">coefficients</span><spanclass="p">[</span><spanclass="mi">0</span><spanclass="p">]</span><spanclass="o">+</span><spanclass="n">other</span><spanclass="p">,)</span>
<spanclass="g g-Whitespace"></span><spanclass="mi">39</span><spanclass="o">+</span><spanclass="bp">self</span><spanclass="o">.</span><spanclass="n">coefficients</span><spanclass="p">[</span><spanclass="mi">1</span><spanclass="p">:])</span>
<spanclass="g g-Whitespace"></span><spanclass="mi">41</span><spanclass="k">elif</span><spanclass="nb">isinstance</span><spanclass="p">(</span><spanclass="n">other</span><spanclass="p">,</span><spanclass="n">Polynomial</span><spanclass="p">):</span>
<spanclass="g g-Whitespace"></span><spanclass="mi">42</span><spanclass="c1"># Work out how many coefficient places the two polynomials have in</span>
<spanclass="g g-Whitespace"></span><spanclass="mi">43</span><spanclass="c1"># common.</span>
<spanclass="g g-Whitespace"></span><spanclass="mi">44</span><spanclass="n">common</span><spanclass="o">=</span><spanclass="nb">min</span><spanclass="p">(</span><spanclass="bp">self</span><spanclass="o">.</span><spanclass="n">degree</span><spanclass="p">(),</span><spanclass="n">other</span><spanclass="o">.</span><spanclass="n">degree</span><spanclass="p">())</span><spanclass="o">+</span><spanclass="mi">1</span>
<spanclass="ne">TypeError</span>: can only concatenate str (not "int") to str
</pre></div>
</div>
<p>This is a much larger error message than those we have previously
encountered, however, the same principles apply. We start by reading
the last line. This tells us that the error was a <aclass="reference external" href="https://docs.python.org/3/library/exceptions.html#TypeError" title="(in Python v3.14)"><codeclass="xref py py-class docutils literal notranslate"><spanclass="pre">TypeError</span></code></a>
caused by attempting to <aclass="reference internal" href="3_objects.html#term-concatenation"><spanclass="xref std std-term">concatenate</span></a> (add) an integer to a
string. Where did this error occur? This is a more involved question
than it may first appear, and the rest of the error message above is
designed to help us answer this question. This type of error message
is called a <aclass="reference internal" href="#term-traceback"><spanclass="xref std std-term">traceback</span></a>, as the second line of the error message
suggests. In order to understand this message, we need to understand a
little about how a Python program is executed, and in particular about
the call stack.</p>
<sectionid="the-call-stack">
<spanid="call-stack"></span><h3><spanclass="section-number">6.3.1. </span>The call stack<aclass="headerlink" href="#the-call-stack" title="Link to this heading">¶</a></h3>
<details>
<summary>
Video: the call stack.</summary><divclass="video_wrapper" style="">
<iframeallowfullscreen="true" src="https://player.vimeo.com/video/509281576" style="border: 0; height: 345px; width: 560px">
</iframe></div><p>Imperial students can also <aclass="reference external" href="https://imperial.cloud.panopto.eu/Panopto/Pages/Viewer.aspx?id=f4fc8938-8e22-47bb-ac78-ae1c00db2e41">watch this video on Panopto</a>.</p>
</details><p>A Python program is a sequence of Python statements, which are
executed in a sequence determined by the flow control logic of the
program itself. Each statement contains zero or more function calls <aclass="footnote-reference brackets" href="#function" id="id2" role="doc-noteref"><spanclass="fn-bracket">[</span>2<spanclass="fn-bracket">]</span></a>,
which are executed in the course of evaluating that statement.</p>
<p>One of the most basic features of a function call is that the contents
of the function execute, and then the code which called the function
continues on from the point of the function call, using the return
value of the function in place of the call. Let’s think about what
happens when this occurs. Before calling the function, there is a
large amount of information which describes the context of the current
program execution. For example, there are all of the module, function,
and variable names which are in scope, and there is the record of
which instruction is next to be executed. This collection of
information about the current execution context is called a
<aclass="reference internal" href="#term-stack-frame"><spanclass="xref std std-term">stack frame</span></a>. We learned about <aclass="reference internal" href="5_abstract_data_types.html#term-stack"><spanclass="xref std std-term">stacks</span></a> in
<aclass="reference internal" href="5_abstract_data_types.html#stacks"><spanclass="std std-numref">Section 5.1</span></a>, and the term “stack frame” is not a coincidence. The
Python interpreter maintains a <aclass="reference internal" href="5_abstract_data_types.html#term-stack"><spanclass="xref std std-term">stack</span></a> of stack frames called
the <aclass="reference internal" href="#term-call-stack"><spanclass="xref std std-term">call stack</span></a>. It is also sometimes called the
<aclass="reference internal" href="#term-execution-stack"><spanclass="xref std std-term">execution stack</span></a> or <aclass="reference internal" href="#term-interpreter-stack"><spanclass="xref std std-term">interpreter stack</span></a>.</p>
<p>The first frame on the stack contains the execution context for the
Python script that the user ran or, in the case where the user worked
interactively, for the iPython shell or Jupyter notebook into which
the user was typing. When a function is called, the Python interpreter
creates a new stack frame containing the local execution context of
that function and pushes it onto the call stack. When that function
returns, its stack frame is popped from the call stack, leaving the
interpreter to continue at the next instruction in the stack frame
from which the function was called. Because functions can call
functions which call functions and so on in a nearly limitless
sequence, there can be a number of stack frames in existence at any
time.</p>
</section>
<sectionid="interpreting-tracebacks">
<h3><spanclass="section-number">6.3.2. </span>Interpreting tracebacks<aclass="headerlink" href="#interpreting-tracebacks" title="Link to this heading">¶</a></h3>
<p>Let’s return to the traceback for our erroneous polynomial addition:</p>
<divclass="highlight-ipython3 notranslate"><divclass="highlight"><pre><span></span><spanclass="gp">In [4]: </span><spanclass="nb">print</span><spanclass="p">(</span><spanclass="mi">1</span><spanclass="o">+</span><spanclass="n">p</span><spanclass="p">)</span>
<spanclass="gt">--------------------------------------------------------------------------</span>
<spanclass="ne">TypeError</span><spanclass="g g-Whitespace"></span>Traceback (most recent call last)
<spanclass="n">Cell</span><spanclass="n">In</span><spanclass="p">[</span><spanclass="mi">4</span><spanclass="p">],</span><spanclass="n">line</span><spanclass="mi">1</span>
<spanclass="ne">----> </span><spanclass="mi">1</span><spanclass="nb">print</span><spanclass="p">(</span><spanclass="mi">1</span><spanclass="o">+</span><spanclass="n">p</span><spanclass="p">)</span>
<spanclass="nn">File ~/docs/principles_of_programming/object-oriented-programming/example_code/polynomial.py:59,</span> in <spanclass="ni">Polynomial.__radd__</span><spanclass="nt">(self, other)</span>
<spanclass="g g-Whitespace"></span><spanclass="mi">58</span><spanclass="k">def</span><spanclass="w"></span><spanclass="fm">__radd__</span><spanclass="p">(</span><spanclass="bp">self</span><spanclass="p">,</span><spanclass="n">other</span><spanclass="p">):</span>
<spanclass="ne">---> </span><spanclass="mi">59</span><spanclass="k">return</span><spanclass="bp">self</span><spanclass="o">+</span><spanclass="n">other</span>
<spanclass="nn">File ~/docs/principles_of_programming/object-oriented-programming/example_code/polynomial.py:38,</span> in <spanclass="ni">Polynomial.__add__</span><spanclass="nt">(self, other)</span>
<spanclass="g g-Whitespace"></span><spanclass="mi">36</span><spanclass="k">def</span><spanclass="w"></span><spanclass="fm">__add__</span><spanclass="p">(</span><spanclass="bp">self</span><spanclass="p">,</span><spanclass="n">other</span><spanclass="p">):</span>
<spanclass="g g-Whitespace"></span><spanclass="mi">37</span><spanclass="k">if</span><spanclass="nb">isinstance</span><spanclass="p">(</span><spanclass="n">other</span><spanclass="p">,</span><spanclass="n">Number</span><spanclass="p">):</span>
<spanclass="ne">---> </span><spanclass="mi">38</span><spanclass="k">return</span><spanclass="n">Polynomial</span><spanclass="p">((</span><spanclass="bp">self</span><spanclass="o">.</span><spanclass="n">coefficients</span><spanclass="p">[</span><spanclass="mi">0</span><spanclass="p">]</span><spanclass="o">+</span><spanclass="n">other</span><spanclass="p">,)</span>
<spanclass="g g-Whitespace"></span><spanclass="mi">39</span><spanclass="o">+</span><spanclass="bp">self</span><spanclass="o">.</span><spanclass="n">coefficients</span><spanclass="p">[</span><spanclass="mi">1</span><spanclass="p">:])</span>
<spanclass="g g-Whitespace"></span><spanclass="mi">41</span><spanclass="k">elif</span><spanclass="nb">isinstance</span><spanclass="p">(</span><spanclass="n">other</span><spanclass="p">,</span><spanclass="n">Polynomial</span><spanclass="p">):</span>
<spanclass="g g-Whitespace"></span><spanclass="mi">42</span><spanclass="c1"># Work out how many coefficient places the two polynomials have in</span>
<spanclass="g g-Whitespace"></span><spanclass="mi">43</span><spanclass="c1"># common.</span>
<spanclass="g g-Whitespace"></span><spanclass="mi">44</span><spanclass="n">common</span><spanclass="o">=</span><spanclass="nb">min</span><spanclass="p">(</span><spanclass="bp">self</span><spanclass="o">.</span><spanclass="n">degree</span><spanclass="p">(),</span><spanclass="n">other</span><spanclass="o">.</span><spanclass="n">degree</span><spanclass="p">())</span><spanclass="o">+</span><spanclass="mi">1</span>
<spanclass="ne">TypeError</span>: can only concatenate str (not "int") to str
</pre></div>
</div>
<p>This shows information about a <aclass="reference internal" href="#term-call-stack"><spanclass="xref std std-term">call stack</span></a> comprising three
<aclass="reference internal" href="#term-stack-frame"><spanclass="xref std std-term">stack frames</span></a>. Look first at the bottom-most
frame, which corresponds to the function in which the exception
occurred. The traceback for this frame starts:</p>
<divclass="highlight-ipython3 notranslate"><divclass="highlight"><pre><span></span><spanclass="n">File</span><spanclass="o">~/</span><spanclass="n">docs</span><spanclass="o">/</span><spanclass="n">principles_of_programming</span><spanclass="o">/</span><spanclass="nb">object</span><spanclass="o">-</span><spanclass="n">oriented</span><spanclass="o">-</span><spanclass="n">programming</span><spanclass="o">/</span><spanclass="n">example_code</span><spanclass="o">/</span><spanclass="n">polynomial</span><spanclass="o">.</span><spanclass="n">py</span><spanclass="p">:</span><spanclass="mi">38</span><spanclass="p">,</span><spanclass="ow">in</span><spanclass="n">Polynomial</span><spanclass="o">.</span><spanclass="fm">__add__</span><spanclass="p">(</span><spanclass="bp">self</span><spanclass="p">,</span><spanclass="n">other</span><spanclass="p">)</span>
</pre></div>
</div>
<p>This indicates that the frame describes code in the file <codeclass="xref py py-obj docutils literal notranslate"><spanclass="pre">polynomial.py</span></code>
(which, on the author’s computer, is located in the folder
<codeclass="xref py py-obj docutils literal notranslate"><spanclass="pre">~/principles_of_programming/object-oriented-programming/example_code/</span></code>).
Specifically, the stack frame describes the execution of the <codeclass="xref py py-meth docutils literal notranslate"><spanclass="pre">__add__()</span></code>
method, which is the <aclass="reference internal" href="3_objects.html#term-special-method"><spanclass="xref std std-term">special method</span></a> responsible for polynomial
addition. The lines below this show the line on which execution stopped (line
38, in this case) and a couple of lines on either side, for context.</p>
<p>The stack frame above this shows the function from which the <codeclass="xref py py-meth docutils literal notranslate"><spanclass="pre">__add__()</span></code>
method was called. In this case, this is the reverse addition <aclass="reference internal" href="3_objects.html#term-special-method"><spanclass="xref std std-term">special
method</span></a>, <codeclass="xref py py-meth docutils literal notranslate"><spanclass="pre">__radd__()</span></code>. On line 59 <codeclass="xref py py-meth docutils literal notranslate"><spanclass="pre">__radd__()</span></code> calls <codeclass="xref py py-meth docutils literal notranslate"><spanclass="pre">__add__()</span></code>
through the addition of <codeclass="xref py py-obj docutils literal notranslate"><spanclass="pre">self</span></code> and <codeclass="xref py py-obj docutils literal notranslate"><spanclass="pre">other</span></code>.</p>
<p>Finally, the top stack frame corresponds to the command that the user typed in
iPython. This stack frame looks a little different from the others. Instead of
a file name there and a function name there is <codeclass="xref py py-obj docutils literal notranslate"><spanclass="pre">Cell</span><spanclass="pre">In</span><spanclass="pre">[4],</span><spanclass="pre">line</span><spanclass="pre">1</span></code>. This
indicates that the exception was raised on line 1 of the IPython cell <codeclass="xref py py-obj docutils literal notranslate"><spanclass="pre">In</span><spanclass="pre">[4]</span></code>.</p>
<divclass="admonition hint">
<pclass="admonition-title">Hint</p>
<p>Older versions of Python display less helpful location information for the
top stack frame, so in that case you might see something like
<codeclass="xref py py-obj docutils literal notranslate"><spanclass="pre"><ipython-input-2-c3aeb16193d4></span><spanclass="pre">in</span></code> rather than
<codeclass="xref py py-obj docutils literal notranslate"><spanclass="pre">Cell</span><spanclass="pre">In</span><spanclass="pre">[4],</span><spanclass="pre">line</span><spanclass="pre">1</span></code>.</p>
</div>
<divclass="admonition hint">
<pclass="admonition-title">Hint</p>
<p>The proximate cause of the error will be in the last <aclass="reference internal" href="#term-stack-frame"><spanclass="xref std std-term">stack
frame</span></a> printed, so always read the <aclass="reference internal" href="#term-traceback"><spanclass="xref std std-term">traceback</span></a> from the
bottom up. However, the ultimate cause of the problem may
be further up the <aclass="reference internal" href="#term-call-stack"><spanclass="xref std std-term">call stack</span></a>, so don’t stop reading at the
bottom frame!</p>
</div>
</section>
</section>
<sectionid="raising-exceptions">
<spanid="id3"></span><h2><spanclass="section-number">6.4. </span>Raising exceptions<aclass="headerlink" href="#raising-exceptions" title="Link to this heading">¶</a></h2>
<details>
<summary>
Video: raising an exception.</summary><divclass="video_wrapper" style="">
<iframeallowfullscreen="true" src="https://player.vimeo.com/video/509492490" style="border: 0; height: 345px; width: 560px">
</iframe></div><p>Imperial students can also <aclass="reference external" href="https://imperial.cloud.panopto.eu/Panopto/Pages/Viewer.aspx?id=fe0a11e0-4600-4578-9207-ae1c00db3aa1">watch this video on Panopto</a>.</p>
</details><p>Thus far we’ve noticed that an exception occurs when something goes
wrong in a program, and that the <aclass="reference internal" href="2_programs_in_files.html#term-Python-interpreter"><spanclass="xref std std-term">Python interpreter</span></a> will stop
at that point and print out a <aclass="reference internal" href="#term-traceback"><spanclass="xref std std-term">traceback</span></a>. We’ll now examine the
process by which an exception occurs.</p>
<p>An exception is triggered using the <aclass="reference external" href="https://docs.python.org/3/reference/simple_stmts.html#raise" title="(in Python v3.14)"><codeclass="xref std std-keyword docutils literal notranslate"><spanclass="pre">raise</span></code></a> keyword. For
example, suppose we want to ensure that the input to our Fibonacci
function is an integer. All Python integers are <aclass="reference internal" href="3_objects.html#term-instance"><spanclass="xref std std-term">instances</span></a> of <aclass="reference external" href="https://docs.python.org/3/library/numbers.html#numbers.Integral" title="(in Python v3.14)"><codeclass="xref py py-class docutils literal notranslate"><spanclass="pre">numbers.Integral</span></code></a>, so we can check this. If we
find a non-integer type then the consequence should be a
<aclass="reference external" href="https://docs.python.org/3/library/exceptions.html#TypeError" title="(in Python v3.14)"><codeclass="xref py py-class docutils literal notranslate"><spanclass="pre">TypeError</span></code></a>. This is achieved by <em>raising</em> the appropriate
exception, using the <aclass="reference external" href="https://docs.python.org/3/reference/simple_stmts.html#raise" title="(in Python v3.14)"><codeclass="xref std std-keyword docutils literal notranslate"><spanclass="pre">raise</span></code></a> statement. The keyword
<aclass="reference external" href="https://docs.python.org/3/reference/simple_stmts.html#raise" title="(in Python v3.14)"><codeclass="xref std std-keyword docutils literal notranslate"><spanclass="pre">raise</span></code></a> is followed by the exception. Almost all exceptions
take a string argument, which is the error message to be printed. In
<aclass="reference internal" href="#typesafe-fib"><spanclass="std std-numref">Listing 6.1</span></a>, we inform the user that we were expecting an
integer rather than the type actually provided.</p>
<divclass="literal-block-wrapper docutils container" id="id7">
<spanid="typesafe-fib"></span><divclass="code-block-caption"><spanclass="caption-number">Listing 6.1 </span><spanclass="caption-text">A version of the Fibonacci function which raises an
exception if a non-integer type is passed as the
argument.</span><aclass="headerlink" href="#id7" title="Link to this code">¶</a></div>
<divclass="highlight-python3 notranslate"><divclass="highlight"><pre><span></span><spanclass="linenos"> 1</span><spanclass="kn">from</span><spanclass="w"></span><spanclass="nn">numbers</span><spanclass="w"></span><spanclass="kn">import</span><spanclass="n">Integral</span>
<spanclass="linenos"> 2</span>
<spanclass="linenos"> 3</span>
<spanclass="linenos"> 4</span><spanclass="k">def</span><spanclass="w"></span><spanclass="nf">typesafe_fib</span><spanclass="p">(</span><spanclass="n">n</span><spanclass="p">):</span>
<spanclass="linenos"> 5</span><spanclass="w"></span><spanclass="sd">"""Return the n-th Fibonacci number, raising an exception if a</span>
<spanclass="linenos"> 6</span><spanclass="sd"> non-integer is passed as n."""</span>
<spanclass="linenos"> 7</span><spanclass="k">if</span><spanclass="ow">not</span><spanclass="nb">isinstance</span><spanclass="p">(</span><spanclass="n">n</span><spanclass="p">,</span><spanclass="n">Integral</span><spanclass="p">):</span>
<spanclass="hll"><spanclass="linenos"> 8</span><spanclass="k">raise</span><spanclass="ne">TypeError</span><spanclass="p">(</span>
</span><spanclass="hll"><spanclass="linenos"> 9</span><spanclass="sa">f</span><spanclass="s2">"fib expects an integer, not a </span><spanclass="si">{</span><spanclass="nb">type</span><spanclass="p">(</span><spanclass="n">n</span><spanclass="p">)</span><spanclass="o">.</span><spanclass="vm">__name__</span><spanclass="si">}</span><spanclass="s2">"</span>
</span><spanclass="hll"><spanclass="linenos">10</span><spanclass="p">)</span>
</span><spanclass="linenos">11</span><spanclass="k">if</span><spanclass="n">n</span><spanclass="o">==</span><spanclass="mi">0</span><spanclass="p">:</span>
<spanclass="linenos">12</span><spanclass="k">return</span><spanclass="mi">0</span>
<spanclass="linenos">13</span><spanclass="k">elif</span><spanclass="n">n</span><spanclass="o">==</span><spanclass="mi">1</span><spanclass="p">:</span>
<spanclass="linenos">14</span><spanclass="k">return</span><spanclass="mi">1</span>
<spanclass="linenos">15</span><spanclass="k">else</span><spanclass="p">:</span>
<spanclass="linenos">16</span><spanclass="k">return</span><spanclass="n">fib</span><spanclass="p">(</span><spanclass="n">n</span><spanclass="o">-</span><spanclass="mi">2</span><spanclass="p">)</span><spanclass="o">+</span><spanclass="n">fib</span><spanclass="p">(</span><spanclass="n">n</span><spanclass="o">-</span><spanclass="mi">1</span><spanclass="p">)</span>
</pre></div>
</div>
</div>
<p>If we now pass a non-integer value to this function, we observe the following:</p>
<divclass="highlight-ipython3 notranslate"><divclass="highlight"><pre><span></span><spanclass="gp">In [1]: </span><spanclass="kn">from</span><spanclass="w"></span><spanclass="nn">fibonacci.typesafe_fibonacci</span><spanclass="w"></span><spanclass="kn">import</span><spanclass="n">typesafe_fib</span>
<spanclass="gp">In [2]: </span><spanclass="n">typesafe_fib</span><spanclass="p">(</span><spanclass="mf">1.5</span><spanclass="p">)</span>
<spanclass="gt">--------------------------------------------------------------------------</span>
<spanclass="ne">TypeError</span><spanclass="g g-Whitespace"></span>Traceback (most recent call last)
<spanclass="n">Cell</span><spanclass="n">In</span><spanclass="p">[</span><spanclass="mi">2</span><spanclass="p">],</span><spanclass="n">line</span><spanclass="mi">1</span>
<spanclass="ne">----> </span><spanclass="mi">1</span><spanclass="n">typesafe_fib</span><spanclass="p">(</span><spanclass="mf">1.5</span><spanclass="p">)</span>
<spanclass="nn">File ~/docs/principles_of_programming/object-oriented-programming/fibonacci/typesafe_fibonacci.py:8,</span> in <spanclass="ni">typesafe_fib</span><spanclass="nt">(n)</span>
<spanclass="g g-Whitespace"></span><spanclass="mi">5</span><spanclass="w"></span><spanclass="sd">"""Return the n-th Fibonacci number, raising an exception if a</span>
<spanclass="g g-Whitespace"></span><spanclass="mi">6</span><spanclass="sd"> non-integer is passed as n."""</span>
<spanclass="g g-Whitespace"></span><spanclass="mi">7</span><spanclass="k">if</span><spanclass="ow">not</span><spanclass="nb">isinstance</span><spanclass="p">(</span><spanclass="n">n</span><spanclass="p">,</span><spanclass="n">Integral</span><spanclass="p">):</span>
<spanclass="ne">----> </span><spanclass="mi">8</span><spanclass="k">raise</span><spanclass="ne">TypeError</span><spanclass="p">(</span>
<spanclass="g g-Whitespace"></span><spanclass="mi">9</span><spanclass="sa">f</span><spanclass="s2">"fib expects an integer, not a </span><spanclass="si">{</span><spanclass="nb">type</span><spanclass="p">(</span><spanclass="n">n</span><spanclass="p">)</span><spanclass="o">.</span><spanclass="vm">__name__</span><spanclass="si">}</span><spanclass="s2">"</span>
<spanclass="g g-Whitespace"></span><spanclass="mi">10</span><spanclass="p">)</span>
<spanclass="g g-Whitespace"></span><spanclass="mi">11</span><spanclass="k">if</span><spanclass="n">n</span><spanclass="o">==</span><spanclass="mi">0</span><spanclass="p">:</span>
<spanclass="g g-Whitespace"></span><spanclass="mi">12</span><spanclass="k">return</span><spanclass="mi">0</span>
<spanclass="ne">TypeError</span>: fib expects an integer, not a float
</pre></div>
</div>
<p>This is exactly what we have come to expect: execution has stopped and
we see a <aclass="reference internal" href="#term-traceback"><spanclass="xref std std-term">traceback</span></a>. Notice that the final line is the error
message that we passed to <aclass="reference external" href="https://docs.python.org/3/library/exceptions.html#TypeError" title="(in Python v3.14)"><codeclass="xref py py-class docutils literal notranslate"><spanclass="pre">TypeError</span></code></a>. The only difference
between this and the previous errors we have seen is that the bottom
<aclass="reference internal" href="#term-stack-frame"><spanclass="xref std std-term">stack frame</span></a> explicitly shows the exception being raised, while
previously the stack showed a piece of code where an error had
occurred. This minor difference has to do with whether the particular
piece of code where the exception occurred is written in Python, or is
written in a language such as C and called from Python. This
distinction is of negligible importance for our current purposes.</p>
<divclass="admonition note">
<pclass="admonition-title">Note</p>
<p>An exceptionally common mistake that programmers make when first
trying to work with exceptions is to write:</p>
<divclass="badcode docutils container">
<divclass="highlight-python3 notranslate"><divclass="highlight"><pre><span></span><spanclass="k">return</span><spanclass="ne">Exception</span>
</pre></div>
</div>
</div>
<p>instead of:</p>
<divclass="goodcode docutils container">
<divclass="highlight-python3 notranslate"><divclass="highlight"><pre><span></span><spanclass="k">raise</span><spanclass="ne">Exception</span>
</pre></div>
</div>
</div>
<p>This mistake is the result of a confusion about what
<aclass="reference external" href="https://docs.python.org/3/reference/simple_stmts.html#return" title="(in Python v3.14)"><codeclass="xref std std-keyword docutils literal notranslate"><spanclass="pre">return</span></code></a> and <aclass="reference external" href="https://docs.python.org/3/reference/simple_stmts.html#raise" title="(in Python v3.14)"><codeclass="xref std std-keyword docutils literal notranslate"><spanclass="pre">raise</span></code></a> do. <aclass="reference external" href="https://docs.python.org/3/reference/simple_stmts.html#return" title="(in Python v3.14)"><codeclass="xref std std-keyword docutils literal notranslate"><spanclass="pre">return</span></code></a> means
“the function is finished, here is the result”. <aclass="reference external" href="https://docs.python.org/3/reference/simple_stmts.html#raise" title="(in Python v3.14)"><codeclass="xref std std-keyword docutils literal notranslate"><spanclass="pre">raise</span></code></a>
means “something exceptional happened, execution is stopping
without a result”.</p>
</div>
</section>
<sectionid="handling-exceptions">
<spanid="id4"></span><h2><spanclass="section-number">6.5. </span>Handling exceptions<aclass="headerlink" href="#handling-exceptions" title="Link to this heading">¶</a></h2>
<details>
<summary>
Video: handling exceptions.</summary><divclass="video_wrapper" style="">
<iframeallowfullscreen="true" src="https://player.vimeo.com/video/509492495" style="border: 0; height: 345px; width: 560px">
</iframe></div><p>Imperial students can also <aclass="reference external" href="https://imperial.cloud.panopto.eu/Panopto/Pages/Viewer.aspx?id=1dfd1930-5b27-4858-8fd1-ae1c00db4473">watch this video on Panopto</a>.</p>
</details><p>So far we have seen several different sorts of exception, how to raise them,
and how to understand the resulting <aclass="reference internal" href="#term-traceback"><spanclass="xref std std-term">traceback</span></a>. The <aclass="reference internal" href="#term-traceback"><spanclass="xref std std-term">traceback</span></a> is
very helpful if the exception was caused by a bug in our code, as it is a rich
source of the information needed to understand and correct the error. However,
sometimes an exception is a valid result of a valid input, and we just need the
program to do something out of the ordinary to deal with the situation. For
example, Euclid’s algorithm for finding the greatest common divisor of
<spanclass="math notranslate nohighlight">\(a\)</span> and <spanclass="math notranslate nohighlight">\(b\)</span> can very nearly be written recursively as:</p>
<divclass="highlight-python notranslate"><divclass="highlight"><pre><span></span><spanclass="k">def</span><spanclass="w"></span><spanclass="nf">gcd</span><spanclass="p">(</span><spanclass="n">a</span><spanclass="p">,</span><spanclass="n">b</span><spanclass="p">):</span>
<spanclass="k">return</span><spanclass="n">gcd</span><spanclass="p">(</span><spanclass="n">b</span><spanclass="p">,</span><spanclass="n">a</span><spanclass="o">%</span><spanclass="n">b</span><spanclass="p">)</span>
</pre></div>
</div>
<p>This works right up to the point where <codeclass="xref py py-obj docutils literal notranslate"><spanclass="pre">b</span></code> becomes zero, at which
point we should stop the recursion and return <codeclass="xref py py-obj docutils literal notranslate"><spanclass="pre">a</span></code>. What actually
happens if we run this code? Let’s try:</p>
<divclass="highlight-ipython notranslate"><divclass="highlight"><pre><span></span><spanclass="gp">In [2]: </span><spanclass="n">gcd</span><spanclass="p">(</span><spanclass="mi">10</span><spanclass="p">,</span><spanclass="mi">12</span><spanclass="p">)</span>
<spanclass="gt">--------------------------------------------------------------------------</span>
<spanclass="ne">ZeroDivisionError</span><spanclass="g g-Whitespace"></span>Traceback (most recent call last)
<spanclass="n">Cell</span><spanclass="n">In</span><spanclass="p">[</span><spanclass="mi">2</span><spanclass="p">],</span><spanclass="n">line</span><spanclass="mi">1</span>
<spanclass="ne">----> </span><spanclass="mi">1</span><spanclass="n">gcd</span><spanclass="p">(</span><spanclass="mi">10</span><spanclass="p">,</span><spanclass="mi">12</span><spanclass="p">)</span>
<spanclass="nn">Cell In[1], line 2,</span> in <spanclass="ni">gcd</span><spanclass="nt">(a, b)</span>
<spanclass="g g-Whitespace"></span><spanclass="mi">1</span><spanclass="k">def</span><spanclass="w"></span><spanclass="nf">gcd</span><spanclass="p">(</span><spanclass="n">a</span><spanclass="p">,</span><spanclass="n">b</span><spanclass="p">):</span>
<spanclass="ne">----> </span><spanclass="mi">2</span><spanclass="k">return</span><spanclass="n">gcd</span><spanclass="p">(</span><spanclass="n">b</span><spanclass="p">,</span><spanclass="n">a</span><spanclass="o">%</span><spanclass="n">b</span><spanclass="p">)</span>
<spanclass="nn">Cell In[1], line 2,</span> in <spanclass="ni">gcd</span><spanclass="nt">(a, b)</span>
<spanclass="g g-Whitespace"></span><spanclass="mi">1</span><spanclass="k">def</span><spanclass="w"></span><spanclass="nf">gcd</span><spanclass="p">(</span><spanclass="n">a</span><spanclass="p">,</span><spanclass="n">b</span><spanclass="p">):</span>
<spanclass="ne">----> </span><spanclass="mi">2</span><spanclass="k">return</span><spanclass="n">gcd</span><spanclass="p">(</span><spanclass="n">b</span><spanclass="p">,</span><spanclass="n">a</span><spanclass="o">%</span><spanclass="n">b</span><spanclass="p">)</span>
<spanclass="p">[</span><spanclass="o">...</span><spanclass="n">skipping</span><spanclass="n">similar</span><spanclass="n">frames</span><spanclass="p">:</span><spanclass="n">gcd</span><spanclass="n">at</span><spanclass="n">line</span><spanclass="mi">2</span><spanclass="p">(</span><spanclass="mi">1</span><spanclass="n">times</span><spanclass="p">)]</span>
<spanclass="nn">Cell In[1], line 2,</span> in <spanclass="ni">gcd</span><spanclass="nt">(a, b)</span>
<spanclass="g g-Whitespace"></span><spanclass="mi">1</span><spanclass="k">def</span><spanclass="w"></span><spanclass="nf">gcd</span><spanclass="p">(</span><spanclass="n">a</span><spanclass="p">,</span><spanclass="n">b</span><spanclass="p">):</span>
<spanclass="ne">----> </span><spanclass="mi">2</span><spanclass="k">return</span><spanclass="n">gcd</span><spanclass="p">(</span><spanclass="n">b</span><spanclass="p">,</span><spanclass="n">a</span><spanclass="o">%</span><spanclass="n">b</span><spanclass="p">)</span>
<spanclass="ne">ZeroDivisionError</span>: integer modulo by zero
</pre></div>
</div>
<p>Notice how the recursive call to <codeclass="xref py py-func docutils literal notranslate"><spanclass="pre">gcd()</span></code> causes several
<aclass="reference internal" href="#term-stack-frame"><spanclass="xref std std-term">stack frames</span></a> that look the same. Indeed, the Python
interpreter even notices the similarity and skips over one. That makes
sense: <codeclass="xref py py-func docutils literal notranslate"><spanclass="pre">gcd()</span></code> calls itself until <codeclass="xref py py-obj docutils literal notranslate"><spanclass="pre">b</span></code> is zero, and then we get a
<aclass="reference external" href="https://docs.python.org/3/library/exceptions.html#ZeroDivisionError" title="(in Python v3.14)"><codeclass="xref py py-class docutils literal notranslate"><spanclass="pre">ZeroDivisionError</span></code></a> because modulo zero is undefined. To
complete this function, what we need to do is to tell Python to stop
at the <aclass="reference external" href="https://docs.python.org/3/library/exceptions.html#ZeroDivisionError" title="(in Python v3.14)"><codeclass="xref py py-class docutils literal notranslate"><spanclass="pre">ZeroDivisionError</span></code></a> and return <codeclass="xref py py-obj docutils literal notranslate"><spanclass="pre">a</span></code>
instead. <aclass="reference internal" href="#gcd"><spanclass="std std-numref">Listing 6.2</span></a> illustrates how this can be achieved.</p>
<divclass="literal-block-wrapper docutils container" id="id8">
<spanid="gcd"></span><divclass="code-block-caption"><spanclass="caption-number">Listing 6.2 </span><spanclass="caption-text">A recursive implementation of Euclid’s algorithm which
catches the <aclass="reference external" href="https://docs.python.org/3/library/exceptions.html#ZeroDivisionError" title="(in Python v3.14)"><codeclass="xref py py-class docutils literal notranslate"><spanclass="pre">ZeroDivisionError</span></code></a> to implement the
base case.</span><aclass="headerlink" href="#id8" title="Link to this code">¶</a></div>
<divclass="highlight-python3 notranslate"><divclass="highlight"><pre><span></span><spanclass="linenos">1</span><spanclass="k">def</span><spanclass="w"></span><spanclass="nf">gcd</span><spanclass="p">(</span><spanclass="n">a</span><spanclass="p">,</span><spanclass="n">b</span><spanclass="p">):</span>
<spanclass="hll"><spanclass="linenos">2</span><spanclass="k">try</span><spanclass="p">:</span>
</span><spanclass="linenos">3</span><spanclass="k">return</span><spanclass="n">gcd</span><spanclass="p">(</span><spanclass="n">b</span><spanclass="p">,</span><spanclass="n">a</span><spanclass="o">%</span><spanclass="n">b</span><spanclass="p">)</span>
<spanclass="hll"><spanclass="linenos">4</span><spanclass="k">except</span><spanclass="ne">ZeroDivisionError</span><spanclass="p">:</span>
</span><spanclass="hll"><spanclass="linenos">5</span><spanclass="k">return</span><spanclass="n">a</span>
</span></pre></div>
</div>
</div>
<p>The new structure here is the <aclass="reference external" href="https://docs.python.org/3/reference/compound_stmts.html#try" title="(in Python v3.14)"><codeclass="xref std std-keyword docutils literal notranslate"><spanclass="pre">try</span></code></a>… <aclass="reference external" href="https://docs.python.org/3/reference/compound_stmts.html#except" title="(in Python v3.14)"><codeclass="xref std std-keyword docutils literal notranslate"><spanclass="pre">except</span></code></a>
block. The <aclass="reference external" href="https://docs.python.org/3/reference/compound_stmts.html#try" title="(in Python v3.14)"><codeclass="xref std std-keyword docutils literal notranslate"><spanclass="pre">try</span></code></a> keyword defines a block of code, in this
case just containing <codeclass="xref py py-obj docutils literal notranslate"><spanclass="pre">return</span><spanclass="pre">gcd(b,</span><spanclass="pre">a</span><spanclass="pre">%</span><spanclass="pre">b)</span></code>. The <aclass="reference external" href="https://docs.python.org/3/reference/compound_stmts.html#except" title="(in Python v3.14)"><codeclass="xref std std-keyword docutils literal notranslate"><spanclass="pre">except</span></code></a> is
optionally followed by an exception class, or a tuple of exception
classes. This case, the <aclass="reference external" href="https://docs.python.org/3/reference/compound_stmts.html#except" title="(in Python v3.14)"><codeclass="xref std std-keyword docutils literal notranslate"><spanclass="pre">except</span></code></a> is only followed by the
<aclass="reference external" href="https://docs.python.org/3/library/exceptions.html#ZeroDivisionError" title="(in Python v3.14)"><codeclass="xref py py-class docutils literal notranslate"><spanclass="pre">ZeroDivisionError</span></code></a> class. What this means is that if a
<aclass="reference external" href="https://docs.python.org/3/library/exceptions.html#ZeroDivisionError" title="(in Python v3.14)"><codeclass="xref py py-class docutils literal notranslate"><spanclass="pre">ZeroDivisionError</span></code></a> is raised by any of the code inside the
<aclass="reference external" href="https://docs.python.org/3/reference/compound_stmts.html#try" title="(in Python v3.14)"><codeclass="xref std std-keyword docutils literal notranslate"><spanclass="pre">try</span></code></a> block then, instead of execution halting and a
<aclass="reference internal" href="#term-traceback"><spanclass="xref std std-term">traceback</span></a> being printed, the code inside the <aclass="reference external" href="https://docs.python.org/3/reference/compound_stmts.html#except" title="(in Python v3.14)"><codeclass="xref std std-keyword docutils literal notranslate"><spanclass="pre">except</span></code></a>
block is run.</p>
<p>In the example here, this means that once <codeclass="xref py py-obj docutils literal notranslate"><spanclass="pre">b</span></code> is zero, instead of
<codeclass="xref py py-obj docutils literal notranslate"><spanclass="pre">gcd</span></code> being called a further time, a is returned. If we run this
version of <codeclass="xref py py-func docutils literal notranslate"><spanclass="pre">gcd()</span></code> then we have, as we might expect:</p>
<divclass="highlight-ipython3 notranslate"><divclass="highlight"><pre><span></span><spanclass="gp">In [2]: </span><spanclass="n">gcd</span><spanclass="p">(</span><spanclass="mi">10</span><spanclass="p">,</span><spanclass="mi">12</span><spanclass="p">)</span>
<spanclass="gh">Out[2]: </span><spanclass="go">2</span>
</pre></div>
</div>
<sectionid="except-clauses">
<h3><spanclass="section-number">6.5.1. </span>Except clauses<aclass="headerlink" href="#except-clauses" title="Link to this heading">¶</a></h3>
<details>
<summary>
Video: further exception handling.</summary><divclass="video_wrapper" style="">
<iframeallowfullscreen="true" src="https://player.vimeo.com/video/509492496" style="border: 0; height: 345px; width: 560px">
</iframe></div><p>Imperial students can also <aclass="reference external" href="https://imperial.cloud.panopto.eu/Panopto/Pages/Viewer.aspx?id=4819cfe6-2743-4ed2-986e-af8e00c2198a">watch this video on Panopto</a>.</p>
</details><p>Let’s look in a little more detail at how <aclass="reference external" href="https://docs.python.org/3/reference/compound_stmts.html#except" title="(in Python v3.14)"><codeclass="xref std std-keyword docutils literal notranslate"><spanclass="pre">except</span></code></a> works. The full
version of the except statement takes a tuple of exception classes. If an
exception is raised matching any of the exceptions in that tuple then the code
in the except block is executed.</p>
<p>It’s also possible to have more than one <aclass="reference external" href="https://docs.python.org/3/reference/compound_stmts.html#except" title="(in Python v3.14)"><codeclass="xref std std-keyword docutils literal notranslate"><spanclass="pre">except</span></code></a> block following a
single <aclass="reference external" href="https://docs.python.org/3/reference/compound_stmts.html#try" title="(in Python v3.14)"><codeclass="xref std std-keyword docutils literal notranslate"><spanclass="pre">try</span></code></a> statement. In this case, the first except block for which
the exception matches the list of exceptions is executed. For example:</p>
<divclass="highlight-ipython notranslate"><divclass="highlight"><pre><span></span><spanclass="gp">In [1]: </span><spanclass="k">try</span><spanclass="p">:</span>
<spanclass="go"> ...: 0./0</span>
<spanclass="go"> ...: except TypeError, KeyError:</span>
<spanclass="go"> ...: print("Type or key error")</span>
<spanclass="go"> ...: except ZeroDivisionError:</span>
<spanclass="go"> ...: print("Zero division error")</span>
<spanclass="go"> ...:</span>
<spanclass="go">Zero division error</span>
</pre></div>
</div>
<divclass="admonition note">
<pclass="admonition-title">Note</p>
<p>It is also possible to omit the list of exceptions after <aclass="reference external" href="https://docs.python.org/3/reference/compound_stmts.html#except" title="(in Python v3.14)"><codeclass="xref std std-keyword docutils literal notranslate"><spanclass="pre">except</span></code></a>.
In this case, the except block will match any exception which is raised in
the corresponding try block. Using unconstrained except blocks like this is
a somewhat dangerous strategy. Usually, the except block will be designed
to deal with a particular type of exceptional circumstance. However, an
except block that catches any exception may well be triggered by a completely
different exception, in which case it will just make the error more
confusing by obscuring where the issue actually occurred.</p>
</div>
</section>
<sectionid="else-and-finally">
<spanid="else-finally"></span><h3><spanclass="section-number">6.5.2. </span>Else and finally<aclass="headerlink" href="#else-and-finally" title="Link to this heading">¶</a></h3>
<p>It can also be useful to execute some code only if an exception is not raised.
This can be achieved using an <aclass="reference external" href="https://docs.python.org/3/reference/compound_stmts.html#try" title="(in Python v3.14)"><codeclass="xref std std-keyword docutils literal notranslate"><spanclass="pre">else</span></code></a> clause. An <aclass="reference external" href="https://docs.python.org/3/reference/compound_stmts.html#try" title="(in Python v3.14)"><codeclass="xref std std-keyword docutils literal notranslate"><spanclass="pre">else</span></code></a> clause after a <aclass="reference external" href="https://docs.python.org/3/reference/compound_stmts.html#try" title="(in Python v3.14)"><codeclass="xref std std-keyword docutils literal notranslate"><spanclass="pre">try</span></code></a> block is caused only if no exception was
raised.</p>
<p>It is also sometimes useful to be able to execute some code no matter what
happened in the <aclass="reference external" href="https://docs.python.org/3/reference/compound_stmts.html#try" title="(in Python v3.14)"><codeclass="xref std std-keyword docutils literal notranslate"><spanclass="pre">try</span></code></a> block. If there is a <aclass="reference external" href="https://docs.python.org/3/reference/compound_stmts.html#finally" title="(in Python v3.14)"><codeclass="xref std std-keyword docutils literal notranslate"><spanclass="pre">finally</span></code></a> clause
then the code it contains will be executed whether or not an exception is
raised and whether or not any exception is handled by an <aclass="reference external" href="https://docs.python.org/3/reference/compound_stmts.html#except" title="(in Python v3.14)"><codeclass="xref std std-keyword docutils literal notranslate"><spanclass="pre">except</span></code></a>
clause. The contents of the <aclass="reference external" href="https://docs.python.org/3/reference/compound_stmts.html#finally" title="(in Python v3.14)"><codeclass="xref std std-keyword docutils literal notranslate"><spanclass="pre">finally</span></code></a> clause will always execute. This
may be useful, for example, if it is necessary to close an external file or
network connection at the end of an operation, even if an exception is raised.
The full details of the <aclass="reference external" href="https://docs.python.org/3/reference/compound_stmts.html#finally" title="(in Python v3.14)"><codeclass="xref std std-keyword docutils literal notranslate"><spanclass="pre">finally</span></code></a> clause are covered in the
<aclass="reference external" href="https://docs.python.org/3/tutorial/errors.html#tut-handling" title="(in Python v3.14)"><spanclass="xref std std-ref">section of the official Python tutorial on handling exceptions</span></a>.</p>
<p>This plethora of variants on the <aclass="reference external" href="https://docs.python.org/3/reference/compound_stmts.html#try" title="(in Python v3.14)"><codeclass="xref std std-keyword docutils literal notranslate"><spanclass="pre">try</span></code></a> block can get a little
confusing, so a practical example may help. <aclass="reference internal" href="#except-demo"><spanclass="std std-numref">Listing 6.3</span></a> prints out a
different message for each type of clause.</p>
<divclass="literal-block-wrapper docutils container" id="id9">
<spanid="except-demo"></span><divclass="code-block-caption"><spanclass="caption-number">Listing 6.3 </span><spanclass="caption-text">A demonstration of all the clauses of the <aclass="reference external" href="https://docs.python.org/3/reference/compound_stmts.html#try" title="(in Python v3.14)"><codeclass="xref std std-keyword docutils literal notranslate"><spanclass="pre">try</span></code></a> block.</span><aclass="headerlink" href="#id9" title="Link to this code">¶</a></div>
<divclass="highlight-python3 notranslate"><divclass="highlight"><pre><span></span><spanclass="linenos"> 1</span><spanclass="k">def</span><spanclass="w"></span><spanclass="nf">except_demo</span><spanclass="p">(</span><spanclass="n">n</span><spanclass="p">):</span>
<spanclass="linenos"> 2</span><spanclass="w"></span><spanclass="sd">"""Demonstrate all the clauses of a `try` block."""</span>
<spanclass="linenos"> 3</span>
<spanclass="linenos"> 4</span><spanclass="nb">print</span><spanclass="p">(</span><spanclass="sa">f</span><spanclass="s2">"Attempting division by </span><spanclass="si">{</span><spanclass="n">n</span><spanclass="si">}</span><spanclass="s2">"</span><spanclass="p">)</span>
<spanclass="linenos"> 5</span><spanclass="k">try</span><spanclass="p">:</span>
<spanclass="linenos"> 6</span><spanclass="nb">print</span><spanclass="p">(</span><spanclass="mf">0.</span><spanclass="o">/</span><spanclass="n">n</span><spanclass="p">)</span>
<spanclass="linenos"> 7</span><spanclass="k">except</span><spanclass="ne">ZeroDivisionError</span><spanclass="p">:</span>
<spanclass="linenos"> 8</span><spanclass="nb">print</span><spanclass="p">(</span><spanclass="s2">"Zero division"</span><spanclass="p">)</span>
<spanclass="linenos"> 9</span><spanclass="k">else</span><spanclass="p">:</span>
<spanclass="linenos">10</span><spanclass="nb">print</span><spanclass="p">(</span><spanclass="s2">"Division successful."</span><spanclass="p">)</span>
<spanclass="linenos">11</span><spanclass="k">finally</span><spanclass="p">:</span>
<spanclass="linenos">12</span><spanclass="nb">print</span><spanclass="p">(</span><spanclass="s2">"Finishing up."</span><spanclass="p">)</span>
</pre></div>
</div>
</div>
<p>If we execute <aclass="reference internal" href="example_code.html#example_code.try_except.except_demo" title="example_code.try_except.except_demo"><codeclass="xref py py-func docutils literal notranslate"><spanclass="pre">except_demo()</span></code></a> for a variety of
arguments, we can observe this complete <aclass="reference external" href="https://docs.python.org/3/reference/compound_stmts.html#try" title="(in Python v3.14)"><codeclass="xref std std-keyword docutils literal notranslate"><spanclass="pre">try</span></code></a> block in action. First,
we provide an input which is a valid divisor:</p>
<divclass="highlight-ipython3 notranslate"><divclass="highlight"><pre><span></span><spanclass="gp">In [1]: </span><spanclass="kn">from</span><spanclass="w"></span><spanclass="nn">example_code.try_except</span><spanclass="w"></span><spanclass="kn">import</span><spanclass="n">except_demo</span>
<spanclass="gp">In [2]: </span><spanclass="n">except_demo</span><spanclass="p">(</span><spanclass="mi">1</span><spanclass="p">)</span>
<spanclass="go">Attempting division by 1</span>
<spanclass="go">0.0</span>
<spanclass="go">Division successful.</span>
<spanclass="go">Finishing up.</span>
</pre></div>
</div>
<p>Here we can see the output of the division, the <aclass="reference external" href="https://docs.python.org/3/reference/compound_stmts.html#try" title="(in Python v3.14)"><codeclass="xref std std-keyword docutils literal notranslate"><spanclass="pre">else</span></code></a> block, and
the <aclass="reference external" href="https://docs.python.org/3/reference/compound_stmts.html#finally" title="(in Python v3.14)"><codeclass="xref std std-keyword docutils literal notranslate"><spanclass="pre">finally</span></code></a> block. Next we divide by zero:</p>
<divclass="highlight-ipython3 notranslate"><divclass="highlight"><pre><span></span><spanclass="gp">In [3]: </span><spanclass="n">except_demo</span><spanclass="p">(</span><spanclass="mi">0</span><spanclass="p">)</span>
<spanclass="go">Attempting division by 0</span>
<spanclass="go">Zero division</span>
<spanclass="go">Finishing up.</span>
</pre></div>
</div>
<p>This caused a <aclass="reference external" href="https://docs.python.org/3/library/exceptions.html#ZeroDivisionError" title="(in Python v3.14)"><codeclass="xref py py-class docutils literal notranslate"><spanclass="pre">ZeroDivisionError</span></code></a>, which was caught by the first
<aclass="reference external" href="https://docs.python.org/3/reference/compound_stmts.html#except" title="(in Python v3.14)"><codeclass="xref std std-keyword docutils literal notranslate"><spanclass="pre">except</span></code></a> clause. Since an exception was raised, the the <aclass="reference external" href="https://docs.python.org/3/reference/compound_stmts.html#try" title="(in Python v3.14)"><codeclass="xref std std-keyword docutils literal notranslate"><spanclass="pre">else</span></code></a> block is not executed, but the <aclass="reference external" href="https://docs.python.org/3/reference/compound_stmts.html#finally" title="(in Python v3.14)"><codeclass="xref std std-keyword docutils literal notranslate"><spanclass="pre">finally</span></code></a> block still executes.
Finally, if we attempt to divide by a string, the exception is not handled, but
the <aclass="reference external" href="https://docs.python.org/3/reference/compound_stmts.html#finally" title="(in Python v3.14)"><codeclass="xref std std-keyword docutils literal notranslate"><spanclass="pre">finally</span></code></a> block executes before the exception causes a traceback:</p>
<divclass="highlight-ipython3 notranslate"><divclass="highlight"><pre><span></span><spanclass="gp">In [4]: </span><spanclass="n">except_demo</span><spanclass="p">(</span><spanclass="s2">"frog"</span><spanclass="p">)</span>
<spanclass="go">Attempting division by frog</span>
<spanclass="go">Finishing up.</span>
<spanclass="gt">---------------------------------------------------------------------------</span>
<spanclass="ne">TypeError</span><spanclass="g g-Whitespace"></span>Traceback (most recent call last)
<spanclass="n">Cell</span><spanclass="n">In</span><spanclass="p">[</span><spanclass="mi">4</span><spanclass="p">],</span><spanclass="n">line</span><spanclass="mi">1</span>
<spanclass="ne">----> </span><spanclass="mi">1</span><spanclass="n">except_demo</span><spanclass="p">(</span><spanclass="s2">"frog"</span><spanclass="p">)</span>
<spanclass="nn">Cell In[3], line 6,</span> in <spanclass="ni">except_demo</span><spanclass="nt">(n)</span>
<spanclass="g g-Whitespace"></span><spanclass="mi">4</span><spanclass="nb">print</span><spanclass="p">(</span><spanclass="sa">f</span><spanclass="s2">"Attempting division by </span><spanclass="si">{</span><spanclass="n">n</span><spanclass="si">}</span><spanclass="s2">"</span><spanclass="p">)</span>
<spanclass="g g-Whitespace"></span><spanclass="mi">5</span><spanclass="k">try</span><spanclass="p">:</span>
<spanclass="ne">----> </span><spanclass="mi">6</span><spanclass="nb">print</span><spanclass="p">(</span><spanclass="mf">0.</span><spanclass="o">/</span><spanclass="n">n</span><spanclass="p">)</span>
<spanclass="g g-Whitespace"></span><spanclass="mi">7</span><spanclass="k">except</span><spanclass="ne">ZeroDivisionError</span><spanclass="p">:</span>
<spanclass="g g-Whitespace"></span><spanclass="mi">8</span><spanclass="nb">print</span><spanclass="p">(</span><spanclass="s2">"Zero division"</span><spanclass="p">)</span>
<spanclass="ne">TypeError</span>: unsupported operand type(s) for /: 'float' and 'str'
</pre></div>
</div>
</section>
<sectionid="exception-handling-and-the-call-stack">
<h3><spanclass="section-number">6.5.3. </span>Exception handling and the call stack<aclass="headerlink" href="#exception-handling-and-the-call-stack" title="Link to this heading">¶</a></h3>
<p>An <aclass="reference external" href="https://docs.python.org/3/reference/compound_stmts.html#except" title="(in Python v3.14)"><codeclass="xref std std-keyword docutils literal notranslate"><spanclass="pre">except</span></code></a> block will handle any matching exception raised in the
preceding <aclass="reference external" href="https://docs.python.org/3/reference/compound_stmts.html#try" title="(in Python v3.14)"><codeclass="xref std std-keyword docutils literal notranslate"><spanclass="pre">try</span></code></a> block. The <aclass="reference external" href="https://docs.python.org/3/reference/compound_stmts.html#try" title="(in Python v3.14)"><codeclass="xref std std-keyword docutils literal notranslate"><spanclass="pre">try</span></code></a> block can, of
course, contain any code at all. In particular it might contain
function calls which themselves may well call further functions. This
means that an exception might occur several <aclass="reference internal" href="#term-stack-frame"><spanclass="xref std std-term">stack frames</span></a> down the <aclass="reference internal" href="#term-call-stack"><spanclass="xref std std-term">call stack</span></a> from the <aclass="reference external" href="https://docs.python.org/3/reference/compound_stmts.html#try" title="(in Python v3.14)"><codeclass="xref std std-keyword docutils literal notranslate"><spanclass="pre">try</span></code></a>
clause. Indeed, some of the functions called might themselves contain
<aclass="reference external" href="https://docs.python.org/3/reference/compound_stmts.html#try" title="(in Python v3.14)"><codeclass="xref std std-keyword docutils literal notranslate"><spanclass="pre">try</span></code></a> blocks with the result that an exception is raised at a
point which is ultimately inside several <aclass="reference external" href="https://docs.python.org/3/reference/compound_stmts.html#try" title="(in Python v3.14)"><codeclass="xref std std-keyword docutils literal notranslate"><spanclass="pre">try</span></code></a> blocks.</p>
<p>The <aclass="reference internal" href="2_programs_in_files.html#term-Python-interpreter"><spanclass="xref std std-term">Python interpreter</span></a> deals with this situation by starting from the
current <aclass="reference internal" href="#term-stack-frame"><spanclass="xref std std-term">stack frame</span></a> and working upwards, a process known as <em>unwinding
the stack</em>. <aclass="reference internal" href="#unwind"><spanclass="std std-numref">Listing 6.4</span></a> shows pseudocode for this process.</p>
<divclass="literal-block-wrapper docutils container" id="id10">
<spanid="unwind"></span><divclass="code-block-caption"><spanclass="caption-number">Listing 6.4 </span><spanclass="caption-text">Pseudocode for the process of <em>unwinding the stack</em>, in which the
interpreter successively looks through higher stack frames to search
for an <aclass="reference external" href="https://docs.python.org/3/reference/compound_stmts.html#except" title="(in Python v3.14)"><codeclass="xref std std-keyword docutils literal notranslate"><spanclass="pre">except</span></code></a> clause matching the exception that has just
been raised.</span><aclass="headerlink" href="#id10" title="Link to this code">¶</a></div>
<divclass="highlight-python3 notranslate"><divclass="highlight"><pre><span></span><spanclass="k">while</span><spanclass="n">call</span><spanclass="n">stack</span><spanclass="ow">not</span><spanclass="n">empty</span><spanclass="p">:</span>
<spanclass="k">if</span><spanclass="n">current</span><spanclass="n">execution</span><spanclass="n">point</span><spanclass="ow">is</span><spanclass="ow">in</span><spanclass="n">a</span><spanclass="k">try</span><spanclass="n">block</span> \
<spanclass="k">with</span><spanclass="n">an</span><spanclass="k">except</span><spanclass="n">matching</span><spanclass="n">the</span><spanclass="n">current</span><spanclass="n">exception</span><spanclass="p">:</span>
<spanclass="n">execution</span><spanclass="n">continues</span><spanclass="ow">in</span><spanclass="n">the</span><spanclass="k">except</span><spanclass="n">block</span>
<spanclass="k">else</span><spanclass="p">:</span>
<spanclass="n">pop</span><spanclass="n">the</span><spanclass="n">current</span><spanclass="n">stack</span><spanclass="n">frame</span><spanclass="n">off</span><spanclass="n">the</span><spanclass="n">call</span><spanclass="n">stack</span>
<spanclass="c1"># Call stack is now empty</span>
<spanclass="nb">print</span><spanclass="n">traceback</span><spanclass="ow">and</span><spanclass="n">exit</span>
</pre></div>
</div>
</div>
</section>
</section>
<sectionid="exceptions-are-not-always-errors">
<h2><spanclass="section-number">6.6. </span>Exceptions are not always errors<aclass="headerlink" href="#exceptions-are-not-always-errors" title="Link to this heading">¶</a></h2>
<p>This chapter is called “Errors and exceptions”, so it is appropriate
to finish by drawing attention to the distinction between these two
concepts. While user errors and bugs in programs typically result in
an exception being raised, it is not the case that all exceptions
result from errors. The name “exception” means what it says, it is an
event whose occurrence requires an exception to the normal sequence of
execution.</p>
<p>The <aclass="reference external" href="https://docs.python.org/3/library/exceptions.html#StopIteration" title="(in Python v3.14)"><codeclass="xref py py-class docutils literal notranslate"><spanclass="pre">StopIteration</span></code></a> exception which we encountered in
<aclass="reference internal" href="5_abstract_data_types.html#iterator-protocol"><spanclass="std std-numref">Section 5.6</span></a> is a good example of an <aclass="reference internal" href="#term-exception"><spanclass="xref std std-term">exception</span></a>
which does not indicate an error. The end of the set of things to be
iterated over does not indicate that something has gone wrong, but it
is an exception to the usual behaviour of <aclass="reference external" href="https://docs.python.org/3/library/stdtypes.html#iterator.__next__" title="(in Python v3.14)"><codeclass="xref py py-meth docutils literal notranslate"><spanclass="pre">__next__()</span></code></a>,
which Python needs to handle in a different way from simply returning
the next item.</p>
</section>
<sectionid="glossary">
<h2><spanclass="section-number">6.7. </span>Glossary<aclass="headerlink" href="#glossary" title="Link to this heading">¶</a></h2>
<blockquote>
<div><dlclass="simple glossary">
<dtid="term-call-stack">call stack<aclass="headerlink" href="#term-call-stack" title="Link to this term">¶</a></dt><dtid="term-execution-stack">execution stack<aclass="headerlink" href="#term-execution-stack" title="Link to this term">¶</a></dt><dtid="term-interpreter-stack">interpreter stack<aclass="headerlink" href="#term-interpreter-stack" title="Link to this term">¶</a></dt><dd><p>The <aclass="reference internal" href="5_abstract_data_types.html#term-stack"><spanclass="xref std std-term">stack</span></a> of <aclass="reference internal" href="#term-stack-frame"><spanclass="xref std std-term">stack frames</span></a> in existence. The
current item on the stack is the currently executing function,
while the deepest item is the stack frame corresponding to the
user script or interpreter.</p>
</dd>
<dtid="term-exception">exception<aclass="headerlink" href="#term-exception" title="Link to this term">¶</a></dt><dd><p>An object representing an out of the ordinary event which has
occurred during the execution of some Python code. When an
exception is <aclass="reference internal" href="#raising-exceptions"><spanclass="std std-ref">raised</span></a> the
<aclass="reference internal" href="2_programs_in_files.html#term-Python-interpreter"><spanclass="xref std std-term">Python interpreter</span></a> doesn’t continue to execute the
following line of code. Instead, the exception is either
<aclass="reference internal" href="#handling-exceptions"><spanclass="std std-ref">handled</span></a> or execution stops and a
<aclass="reference internal" href="#term-traceback"><spanclass="xref std std-term">traceback</span></a> is printed.</p>
</dd>
<dtid="term-stack-frame">stack frame<aclass="headerlink" href="#term-stack-frame" title="Link to this term">¶</a></dt><dd><p>An object encapsulating the set of variables which define the
execution of a Python script or function. This information
includes the code being executed, all the local and global
names which are visible, the last instruction that was
executed, and a reference to the stack frame which called this
function.</p>
</dd>
<dtid="term-syntax">syntax<aclass="headerlink" href="#term-syntax" title="Link to this term">¶</a></dt><dd><p>The set of rules which define what is a well-formed Python
statement. For example the rule that statements which start
blocks must end with a colon (:) is a syntax rule.</p>
</dd>
<dtid="term-syntax-error">syntax error<aclass="headerlink" href="#term-syntax-error" title="Link to this term">¶</a></dt><dd><p>The <aclass="reference internal" href="#term-exception"><spanclass="xref std std-term">exception</span></a> which occurs when a statement violates
the <aclass="reference internal" href="#term-syntax"><spanclass="xref std std-term">syntax</span></a> rules of Python. Mismatched brackets,
missing commas, and incorrect indentation are all examples of
syntax errors.</p>
</dd>
<dtid="term-traceback">traceback<aclass="headerlink" href="#term-traceback" title="Link to this term">¶</a></dt><dtid="term-stack-trace">stack trace<aclass="headerlink" href="#term-stack-trace" title="Link to this term">¶</a></dt><dtid="term-back-trace">back trace<aclass="headerlink" href="#term-back-trace" title="Link to this term">¶</a></dt><dd><p>A text representation of the <aclass="reference internal" href="#term-call-stack"><spanclass="xref std std-term">call stack</span></a>. A traceback
shows a few lines of code around the current execution point
in each <aclass="reference internal" href="#term-stack-frame"><spanclass="xref std std-term">stack frame</span></a>, with the current frame at the
bottom and the outermost frame at the top.</p>
</dd>
</dl>
</div></blockquote>
</section>
<sectionid="exercises">
<h2><spanclass="section-number">6.8. </span>Exercises<aclass="headerlink" href="#exercises" title="Link to this heading">¶</a></h2>
<p>Using the information on the <aclass="reference external" href="https://object-oriented-python.github.io/edition3/exercises.html">book website</a>
obtain the skeleton code for these exercises.</p>
<divclass="proof proof-type-exercise" id="id11">
<divclass="proof-title">
<spanclass="proof-type">Exercise 6.1</span>
</div><divclass="proof-content">
<p>The Newton-Raphson method is an iterative method for approximately solving
equations of the form <spanclass="math notranslate nohighlight">\(f(x)=0\)</span>. Starting from an initial guess, a
series of (hopefully convergent) approximations to the solution is computed:</p>
<divclass="math notranslate nohighlight">
\[x_{n+1} = x_n - \frac{f(x_n)}{f'(x_n)}\]</div>
<p>The iteration concludes successfully if <spanclass="math notranslate nohighlight">\(|f(x_{n+1})| < \epsilon\)</span> for some
user-specified tolerance <spanclass="math notranslate nohighlight">\(\epsilon>0\)</span>. The sequence is not guaranteed
to converge for all combinations of function and starting point, so the
iteration should fail if <spanclass="math notranslate nohighlight">\(n\)</span> exceeds a user-specified number of
iterations.</p>
<p>The skeleton code for this chapter contains a function
<codeclass="xref py py-func docutils literal notranslate"><spanclass="pre">nonlinear_solvers.solvers.newton_raphson()</span></code> which takes as arguments a
function, its derivative and a starting point for the iteration. It can also
optionally be passed a value for <spanclass="math notranslate nohighlight">\(\epsilon\)</span> and a maximum number of
iterations to execute. Implement this function. If the iteration succeeds
then the last iterate, <spanclass="math notranslate nohighlight">\(x_{n+1}\)</span>, should be returned.</p>
<p><codeclass="xref py py-mod docutils literal notranslate"><spanclass="pre">nonlinear_solvers.solvers</span></code> also defines an exception,
<codeclass="xref py py-class docutils literal notranslate"><spanclass="pre">ConvergenceError</span></code>. If the Newton-Raphson iteration exceeds the
number of iterations allowed then this exception should be raised, with an
appropriate error message.</p>
</div></div><divclass="proof proof-type-exercise" id="id12">
<divclass="proof-title">
<spanclass="proof-type">Exercise 6.2</span>
</div><divclass="proof-content">
<p>The bisection method is a slower but more robust iterative solver. It requires a
function <spanclass="math notranslate nohighlight">\(f\)</span> and two starting points <spanclass="math notranslate nohighlight">\(x_0\)</span> and <spanclass="math notranslate nohighlight">\(x_1\)</span> such
that <spanclass="math notranslate nohighlight">\(f(x_0)\)</span> and <spanclass="math notranslate nohighlight">\(f(x_1)\)</span> differ in sign. At each stage of the
iteration, the function is evaluated at the midpoint of the current points
<spanclass="math notranslate nohighlight">\(x^* = (x_0 + x_1)/2\)</span>. If <spanclass="math notranslate nohighlight">\(|\,f(x^*)|<\epsilon\)</span> then the iteration
terminates successfully. Otherwise, <spanclass="math notranslate nohighlight">\(x^*\)</span> replaces <spanclass="math notranslate nohighlight">\(x_0\)</span> if
<spanclass="math notranslate nohighlight">\(f(x_0)\)</span> and <spanclass="math notranslate nohighlight">\(f(x^*)\)</span> have the same sign, and replaces
<spanclass="math notranslate nohighlight">\(x_1\)</span> otherwise.</p>
<p>Implement <codeclass="xref py py-func docutils literal notranslate"><spanclass="pre">nonlinear_solvers.solvers.bisection()</span></code>. As before, if the
iteration succeeds then return the last value of <spanclass="math notranslate nohighlight">\(x\)</span>. If the maximum
number of iterations is exceeded, raise <codeclass="xref py py-class docutils literal notranslate"><spanclass="pre">ConvergenceError</span></code> with a
suitable error message. The bisection method has a further failure mode. If
<spanclass="math notranslate nohighlight">\(f(x_0)\)</span> and <spanclass="math notranslate nohighlight">\(f(x_1)\)</span> do not differ in sign then your code
should raise <aclass="reference external" href="https://docs.python.org/3/library/exceptions.html#ValueError" title="(in Python v3.14)"><codeclass="xref py py-class docutils literal notranslate"><spanclass="pre">ValueError</span></code></a> with a suitable message.</p>
</div></div><divclass="proof proof-type-exercise" id="id13">
<divclass="proof-title">
<spanclass="proof-type">Exercise 6.3</span>
</div><divclass="proof-content">
<p>Implement the function <codeclass="xref py py-func docutils literal notranslate"><spanclass="pre">nonlinear_solvers.solvers.solve()</span></code>. This code
should first attempt to solve <spanclass="math notranslate nohighlight">\(f(x)=0\)</span> using your Newton-Raphson
function. If that fails it should catch the exception and instead try using
your bisection function.</p>
</div></div><pclass="rubric">Footnotes</p>
<asideclass="footnote-list brackets">
<asideclass="footnote brackets" id="tut-exceptions" role="doc-footnote">
<spanclass="label"><spanclass="fn-bracket">[</span><arole="doc-backlink" href="#id5">1</a><spanclass="fn-bracket">]</span></span>
<p><aclass="reference external" href="https://docs.python.org/3/tutorial/errors.html#tut-handling">https://docs.python.org/3/tutorial/errors.html#tut-handling</a></p>
</aside>
<asideclass="footnote brackets" id="function" role="doc-footnote">
<spanclass="label"><spanclass="fn-bracket">[</span><arole="doc-backlink" href="#id2">2</a><spanclass="fn-bracket">]</span></span>
<p>“Function call” here includes <aclass="reference internal" href="3_objects.html#term-method"><spanclass="xref std std-term">method</span></a> calls and
operations implemented using a <aclass="reference internal" href="3_objects.html#term-special-method"><spanclass="xref std std-term">special method</span></a>.</p>
</aside>
<asideclass="footnote brackets" id="exercise-page" role="doc-footnote">
<spanclass="label"><spanclass="fn-bracket">[</span><arole="doc-backlink" href="#id6">3</a><spanclass="fn-bracket">]</span></span>
<p><aclass="reference external" href="https://object-oriented-python.github.io/edition3/exercises.html">https://object-oriented-python.github.io/edition3/exercises.html</a></p>
</aside>
</aside>
</section>
</section>
<divclass="clearer"></div>
</div>
</div>
</div>
<divclass="clearer"></div>
</div>
<divclass="footer" role="contentinfo">
© Copyright 2019-2023, David A. Ham.
Created using <ahref="https://www.sphinx-doc.org/">Sphinx</a> 7.4.7.
</div>
</body>
</html>