errors.html 77 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924
  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <meta charset="utf-8" />
  5. <meta name="viewport" content="width=device-width, initial-scale=1.0" /><meta name="generator" content="Docutils 0.17.1: http://docutils.sourceforge.net/" />
  6. <meta property="og:title" content="8. Errors and Exceptions" />
  7. <meta property="og:type" content="website" />
  8. <meta property="og:url" content="https://docs.python.org/3/tutorial/errors.html" />
  9. <meta property="og:site_name" content="Python documentation" />
  10. <meta property="og:description" content="Until now error messages haven’t been more than mentioned, but if you have tried out the examples you have probably seen some. There are (at least) two distinguishable kinds of errors: syntax error..." />
  11. <meta property="og:image" content="https://docs.python.org/3/_static/og-image.png" />
  12. <meta property="og:image:alt" content="Python documentation" />
  13. <meta name="description" content="Until now error messages haven’t been more than mentioned, but if you have tried out the examples you have probably seen some. There are (at least) two distinguishable kinds of errors: syntax error..." />
  14. <meta property="og:image:width" content="200" />
  15. <meta property="og:image:height" content="200" />
  16. <meta name="theme-color" content="#3776ab" />
  17. <title>8. Errors and Exceptions &#8212; Python 3.12.0 documentation</title><meta name="viewport" content="width=device-width, initial-scale=1.0">
  18. <link rel="stylesheet" type="text/css" href="../_static/pygments.css" />
  19. <link rel="stylesheet" type="text/css" href="../_static/pydoctheme.css?digest=b37c26da2f7529d09fe70b41c4b2133fe4931a90" />
  20. <link id="pygments_dark_css" media="(prefers-color-scheme: dark)" rel="stylesheet" type="text/css" href="../_static/pygments_dark.css" />
  21. <script data-url_root="../" id="documentation_options" src="../_static/documentation_options.js"></script>
  22. <script src="../_static/jquery.js"></script>
  23. <script src="../_static/underscore.js"></script>
  24. <script src="../_static/doctools.js"></script>
  25. <script src="../_static/sidebar.js"></script>
  26. <link rel="search" type="application/opensearchdescription+xml"
  27. title="Search within Python 3.12.0 documentation"
  28. href="../_static/opensearch.xml"/>
  29. <link rel="author" title="About these documents" href="../about.html" />
  30. <link rel="index" title="Index" href="../genindex.html" />
  31. <link rel="search" title="Search" href="../search.html" />
  32. <link rel="copyright" title="Copyright" href="../copyright.html" />
  33. <link rel="next" title="9. Classes" href="classes.html" />
  34. <link rel="prev" title="7. Input and Output" href="inputoutput.html" />
  35. <link rel="canonical" href="https://docs.python.org/3/tutorial/errors.html" />
  36. <style>
  37. @media only screen {
  38. table.full-width-table {
  39. width: 100%;
  40. }
  41. }
  42. </style>
  43. <link rel="stylesheet" href="../_static/pydoctheme_dark.css" media="(prefers-color-scheme: dark)" id="pydoctheme_dark_css">
  44. <link rel="shortcut icon" type="image/png" href="../_static/py.svg" />
  45. <script type="text/javascript" src="../_static/copybutton.js"></script>
  46. <script type="text/javascript" src="../_static/menu.js"></script>
  47. <script type="text/javascript" src="../_static/themetoggle.js"></script>
  48. </head>
  49. <body>
  50. <div class="mobile-nav">
  51. <input type="checkbox" id="menuToggler" class="toggler__input" aria-controls="navigation"
  52. aria-pressed="false" aria-expanded="false" role="button" aria-label="Menu" />
  53. <nav class="nav-content" role="navigation">
  54. <label for="menuToggler" class="toggler__label">
  55. <span></span>
  56. </label>
  57. <span class="nav-items-wrapper">
  58. <a href="https://www.python.org/" class="nav-logo">
  59. <img src="../_static/py.svg" alt="Logo"/>
  60. </a>
  61. <span class="version_switcher_placeholder"></span>
  62. <form role="search" class="search" action="../search.html" method="get">
  63. <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" class="search-icon">
  64. <path fill-rule="nonzero" fill="currentColor" d="M15.5 14h-.79l-.28-.27a6.5 6.5 0 001.48-5.34c-.47-2.78-2.79-5-5.59-5.34a6.505 6.505 0 00-7.27 7.27c.34 2.8 2.56 5.12 5.34 5.59a6.5 6.5 0 005.34-1.48l.27.28v.79l4.25 4.25c.41.41 1.08.41 1.49 0 .41-.41.41-1.08 0-1.49L15.5 14zm-6 0C7.01 14 5 11.99 5 9.5S7.01 5 9.5 5 14 7.01 14 9.5 11.99 14 9.5 14z"></path>
  65. </svg>
  66. <input placeholder="Quick search" aria-label="Quick search" type="search" name="q" />
  67. <input type="submit" value="Go"/>
  68. </form>
  69. </span>
  70. </nav>
  71. <div class="menu-wrapper">
  72. <nav class="menu" role="navigation" aria-label="main navigation">
  73. <div class="language_switcher_placeholder"></div>
  74. <label class="theme-selector-label">
  75. Theme
  76. <select class="theme-selector" oninput="activateTheme(this.value)">
  77. <option value="auto" selected>Auto</option>
  78. <option value="light">Light</option>
  79. <option value="dark">Dark</option>
  80. </select>
  81. </label>
  82. <div>
  83. <h3><a href="../contents.html">Table of Contents</a></h3>
  84. <ul>
  85. <li><a class="reference internal" href="#">8. Errors and Exceptions</a><ul>
  86. <li><a class="reference internal" href="#syntax-errors">8.1. Syntax Errors</a></li>
  87. <li><a class="reference internal" href="#exceptions">8.2. Exceptions</a></li>
  88. <li><a class="reference internal" href="#handling-exceptions">8.3. Handling Exceptions</a></li>
  89. <li><a class="reference internal" href="#raising-exceptions">8.4. Raising Exceptions</a></li>
  90. <li><a class="reference internal" href="#exception-chaining">8.5. Exception Chaining</a></li>
  91. <li><a class="reference internal" href="#user-defined-exceptions">8.6. User-defined Exceptions</a></li>
  92. <li><a class="reference internal" href="#defining-clean-up-actions">8.7. Defining Clean-up Actions</a></li>
  93. <li><a class="reference internal" href="#predefined-clean-up-actions">8.8. Predefined Clean-up Actions</a></li>
  94. <li><a class="reference internal" href="#raising-and-handling-multiple-unrelated-exceptions">8.9. Raising and Handling Multiple Unrelated Exceptions</a></li>
  95. <li><a class="reference internal" href="#enriching-exceptions-with-notes">8.10. Enriching Exceptions with Notes</a></li>
  96. </ul>
  97. </li>
  98. </ul>
  99. </div>
  100. <div>
  101. <h4>Previous topic</h4>
  102. <p class="topless"><a href="inputoutput.html"
  103. title="previous chapter"><span class="section-number">7. </span>Input and Output</a></p>
  104. </div>
  105. <div>
  106. <h4>Next topic</h4>
  107. <p class="topless"><a href="classes.html"
  108. title="next chapter"><span class="section-number">9. </span>Classes</a></p>
  109. </div>
  110. <div role="note" aria-label="source link">
  111. <h3>This Page</h3>
  112. <ul class="this-page-menu">
  113. <li><a href="../bugs.html">Report a Bug</a></li>
  114. <li>
  115. <a href="https://github.com/python/cpython/blob/main/Doc/tutorial/errors.rst"
  116. rel="nofollow">Show Source
  117. </a>
  118. </li>
  119. </ul>
  120. </div>
  121. </nav>
  122. </div>
  123. </div>
  124. <div class="related" role="navigation" aria-label="related navigation">
  125. <h3>Navigation</h3>
  126. <ul>
  127. <li class="right" style="margin-right: 10px">
  128. <a href="../genindex.html" title="General Index"
  129. accesskey="I">index</a></li>
  130. <li class="right" >
  131. <a href="../py-modindex.html" title="Python Module Index"
  132. >modules</a> |</li>
  133. <li class="right" >
  134. <a href="classes.html" title="9. Classes"
  135. accesskey="N">next</a> |</li>
  136. <li class="right" >
  137. <a href="inputoutput.html" title="7. Input and Output"
  138. accesskey="P">previous</a> |</li>
  139. <li><img src="../_static/py.svg" alt="python logo" style="vertical-align: middle; margin-top: -1px"/></li>
  140. <li><a href="https://www.python.org/">Python</a> &#187;</li>
  141. <li class="switchers">
  142. <div class="language_switcher_placeholder"></div>
  143. <div class="version_switcher_placeholder"></div>
  144. </li>
  145. <li>
  146. </li>
  147. <li id="cpython-language-and-version">
  148. <a href="../index.html">3.12.0 Documentation</a> &#187;
  149. </li>
  150. <li class="nav-item nav-item-1"><a href="index.html" accesskey="U">The Python Tutorial</a> &#187;</li>
  151. <li class="nav-item nav-item-this"><a href=""><span class="section-number">8. </span>Errors and Exceptions</a></li>
  152. <li class="right">
  153. <div class="inline-search" role="search">
  154. <form class="inline-search" action="../search.html" method="get">
  155. <input placeholder="Quick search" aria-label="Quick search" type="search" name="q" />
  156. <input type="submit" value="Go" />
  157. </form>
  158. </div>
  159. |
  160. </li>
  161. <li class="right">
  162. <label class="theme-selector-label">
  163. Theme
  164. <select class="theme-selector" oninput="activateTheme(this.value)">
  165. <option value="auto" selected>Auto</option>
  166. <option value="light">Light</option>
  167. <option value="dark">Dark</option>
  168. </select>
  169. </label> |</li>
  170. </ul>
  171. </div>
  172. <div class="document">
  173. <div class="documentwrapper">
  174. <div class="bodywrapper">
  175. <div class="body" role="main">
  176. <section id="errors-and-exceptions">
  177. <span id="tut-errors"></span><h1><span class="section-number">8. </span>Errors and Exceptions<a class="headerlink" href="#errors-and-exceptions" title="Permalink to this headline">¶</a></h1>
  178. <p>Until now error messages haven’t been more than mentioned, but if you have tried
  179. out the examples you have probably seen some. There are (at least) two
  180. distinguishable kinds of errors: <em>syntax errors</em> and <em>exceptions</em>.</p>
  181. <section id="syntax-errors">
  182. <span id="tut-syntaxerrors"></span><h2><span class="section-number">8.1. </span>Syntax Errors<a class="headerlink" href="#syntax-errors" title="Permalink to this headline">¶</a></h2>
  183. <p>Syntax errors, also known as parsing errors, are perhaps the most common kind of
  184. complaint you get while you are still learning Python:</p>
  185. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="k">while</span> <span class="kc">True</span> <span class="nb">print</span><span class="p">(</span><span class="s1">&#39;Hello world&#39;</span><span class="p">)</span>
  186. File <span class="nb">&quot;&lt;stdin&gt;&quot;</span>, line <span class="m">1</span>
  187. <span class="w"> </span><span class="k">while</span> <span class="kc">True</span> <span class="nb">print</span><span class="p">(</span><span class="s1">&#39;Hello world&#39;</span><span class="p">)</span>
  188. <span class="w"> </span><span class="pm">^</span>
  189. <span class="gr">SyntaxError</span>: <span class="n">invalid syntax</span>
  190. </pre></div>
  191. </div>
  192. <p>The parser repeats the offending line and displays a little ‘arrow’ pointing at
  193. the earliest point in the line where the error was detected. The error is
  194. caused by (or at least detected at) the token <em>preceding</em> the arrow: in the
  195. example, the error is detected at the function <a class="reference internal" href="../library/functions.html#print" title="print"><code class="xref py py-func docutils literal notranslate"><span class="pre">print()</span></code></a>, since a colon
  196. (<code class="docutils literal notranslate"><span class="pre">':'</span></code>) is missing before it. File name and line number are printed so you
  197. know where to look in case the input came from a script.</p>
  198. </section>
  199. <section id="exceptions">
  200. <span id="tut-exceptions"></span><h2><span class="section-number">8.2. </span>Exceptions<a class="headerlink" href="#exceptions" title="Permalink to this headline">¶</a></h2>
  201. <p>Even if a statement or expression is syntactically correct, it may cause an
  202. error when an attempt is made to execute it. Errors detected during execution
  203. are called <em>exceptions</em> and are not unconditionally fatal: you will soon learn
  204. how to handle them in Python programs. Most exceptions are not handled by
  205. programs, however, and result in error messages as shown here:</p>
  206. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="mi">10</span> <span class="o">*</span> <span class="p">(</span><span class="mi">1</span><span class="o">/</span><span class="mi">0</span><span class="p">)</span>
  207. <span class="gt">Traceback (most recent call last):</span>
  208. File <span class="nb">&quot;&lt;stdin&gt;&quot;</span>, line <span class="m">1</span>, in <span class="n">&lt;module&gt;</span>
  209. <span class="gr">ZeroDivisionError</span>: <span class="n">division by zero</span>
  210. <span class="gp">&gt;&gt;&gt; </span><span class="mi">4</span> <span class="o">+</span> <span class="n">spam</span><span class="o">*</span><span class="mi">3</span>
  211. <span class="gt">Traceback (most recent call last):</span>
  212. File <span class="nb">&quot;&lt;stdin&gt;&quot;</span>, line <span class="m">1</span>, in <span class="n">&lt;module&gt;</span>
  213. <span class="gr">NameError</span>: <span class="n">name &#39;spam&#39; is not defined</span>
  214. <span class="gp">&gt;&gt;&gt; </span><span class="s1">&#39;2&#39;</span> <span class="o">+</span> <span class="mi">2</span>
  215. <span class="gt">Traceback (most recent call last):</span>
  216. File <span class="nb">&quot;&lt;stdin&gt;&quot;</span>, line <span class="m">1</span>, in <span class="n">&lt;module&gt;</span>
  217. <span class="gr">TypeError</span>: <span class="n">can only concatenate str (not &quot;int&quot;) to str</span>
  218. </pre></div>
  219. </div>
  220. <p>The last line of the error message indicates what happened. Exceptions come in
  221. different types, and the type is printed as part of the message: the types in
  222. the example are <a class="reference internal" href="../library/exceptions.html#ZeroDivisionError" title="ZeroDivisionError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">ZeroDivisionError</span></code></a>, <a class="reference internal" href="../library/exceptions.html#NameError" title="NameError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">NameError</span></code></a> and <a class="reference internal" href="../library/exceptions.html#TypeError" title="TypeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">TypeError</span></code></a>.
  223. The string printed as the exception type is the name of the built-in exception
  224. that occurred. This is true for all built-in exceptions, but need not be true
  225. for user-defined exceptions (although it is a useful convention). Standard
  226. exception names are built-in identifiers (not reserved keywords).</p>
  227. <p>The rest of the line provides detail based on the type of exception and what
  228. caused it.</p>
  229. <p>The preceding part of the error message shows the context where the exception
  230. occurred, in the form of a stack traceback. In general it contains a stack
  231. traceback listing source lines; however, it will not display lines read from
  232. standard input.</p>
  233. <p><a class="reference internal" href="../library/exceptions.html#bltin-exceptions"><span class="std std-ref">Built-in Exceptions</span></a> lists the built-in exceptions and their meanings.</p>
  234. </section>
  235. <section id="handling-exceptions">
  236. <span id="tut-handling"></span><h2><span class="section-number">8.3. </span>Handling Exceptions<a class="headerlink" href="#handling-exceptions" title="Permalink to this headline">¶</a></h2>
  237. <p>It is possible to write programs that handle selected exceptions. Look at the
  238. following example, which asks the user for input until a valid integer has been
  239. entered, but allows the user to interrupt the program (using <kbd class="kbd compound docutils literal notranslate"><kbd class="kbd docutils literal notranslate">Control</kbd>-<kbd class="kbd docutils literal notranslate">C</kbd></kbd> or
  240. whatever the operating system supports); note that a user-generated interruption
  241. is signalled by raising the <a class="reference internal" href="../library/exceptions.html#KeyboardInterrupt" title="KeyboardInterrupt"><code class="xref py py-exc docutils literal notranslate"><span class="pre">KeyboardInterrupt</span></code></a> exception.</p>
  242. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="k">while</span> <span class="kc">True</span><span class="p">:</span>
  243. <span class="gp">... </span> <span class="k">try</span><span class="p">:</span>
  244. <span class="gp">... </span> <span class="n">x</span> <span class="o">=</span> <span class="nb">int</span><span class="p">(</span><span class="nb">input</span><span class="p">(</span><span class="s2">&quot;Please enter a number: &quot;</span><span class="p">))</span>
  245. <span class="gp">... </span> <span class="k">break</span>
  246. <span class="gp">... </span> <span class="k">except</span> <span class="ne">ValueError</span><span class="p">:</span>
  247. <span class="gp">... </span> <span class="nb">print</span><span class="p">(</span><span class="s2">&quot;Oops! That was no valid number. Try again...&quot;</span><span class="p">)</span>
  248. <span class="gp">...</span>
  249. </pre></div>
  250. </div>
  251. <p>The <a class="reference internal" href="../reference/compound_stmts.html#try"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">try</span></code></a> statement works as follows.</p>
  252. <ul class="simple">
  253. <li><p>First, the <em>try clause</em> (the statement(s) between the <a class="reference internal" href="../reference/compound_stmts.html#try"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">try</span></code></a> and
  254. <a class="reference internal" href="../reference/compound_stmts.html#except"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">except</span></code></a> keywords) is executed.</p></li>
  255. <li><p>If no exception occurs, the <em>except clause</em> is skipped and execution of the
  256. <a class="reference internal" href="../reference/compound_stmts.html#try"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">try</span></code></a> statement is finished.</p></li>
  257. <li><p>If an exception occurs during execution of the <a class="reference internal" href="../reference/compound_stmts.html#try"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">try</span></code></a> clause, the rest of the
  258. clause is skipped. Then, if its type matches the exception named after the
  259. <a class="reference internal" href="../reference/compound_stmts.html#except"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">except</span></code></a> keyword, the <em>except clause</em> is executed, and then execution
  260. continues after the try/except block.</p></li>
  261. <li><p>If an exception occurs which does not match the exception named in the <em>except
  262. clause</em>, it is passed on to outer <a class="reference internal" href="../reference/compound_stmts.html#try"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">try</span></code></a> statements; if no handler is
  263. found, it is an <em>unhandled exception</em> and execution stops with a message as
  264. shown above.</p></li>
  265. </ul>
  266. <p>A <a class="reference internal" href="../reference/compound_stmts.html#try"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">try</span></code></a> statement may have more than one <em>except clause</em>, to specify
  267. handlers for different exceptions. At most one handler will be executed.
  268. Handlers only handle exceptions that occur in the corresponding <em>try clause</em>,
  269. not in other handlers of the same <code class="xref std std-keyword docutils literal notranslate"><span class="pre">try</span></code> statement. An <em>except clause</em>
  270. may name multiple exceptions as a parenthesized tuple, for example:</p>
  271. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="o">...</span> <span class="k">except</span> <span class="p">(</span><span class="ne">RuntimeError</span><span class="p">,</span> <span class="ne">TypeError</span><span class="p">,</span> <span class="ne">NameError</span><span class="p">):</span>
  272. <span class="o">...</span> <span class="k">pass</span>
  273. </pre></div>
  274. </div>
  275. <p>A class in an <a class="reference internal" href="../reference/compound_stmts.html#except"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">except</span></code></a> clause is compatible with an exception if it is
  276. the same class or a base class thereof (but not the other way around — an
  277. <em>except clause</em> listing a derived class is not compatible with a base class).
  278. For example, the following code will print B, C, D in that order:</p>
  279. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">class</span> <span class="nc">B</span><span class="p">(</span><span class="ne">Exception</span><span class="p">):</span>
  280. <span class="k">pass</span>
  281. <span class="k">class</span> <span class="nc">C</span><span class="p">(</span><span class="n">B</span><span class="p">):</span>
  282. <span class="k">pass</span>
  283. <span class="k">class</span> <span class="nc">D</span><span class="p">(</span><span class="n">C</span><span class="p">):</span>
  284. <span class="k">pass</span>
  285. <span class="k">for</span> <span class="bp">cls</span> <span class="ow">in</span> <span class="p">[</span><span class="n">B</span><span class="p">,</span> <span class="n">C</span><span class="p">,</span> <span class="n">D</span><span class="p">]:</span>
  286. <span class="k">try</span><span class="p">:</span>
  287. <span class="k">raise</span> <span class="bp">cls</span><span class="p">()</span>
  288. <span class="k">except</span> <span class="n">D</span><span class="p">:</span>
  289. <span class="nb">print</span><span class="p">(</span><span class="s2">&quot;D&quot;</span><span class="p">)</span>
  290. <span class="k">except</span> <span class="n">C</span><span class="p">:</span>
  291. <span class="nb">print</span><span class="p">(</span><span class="s2">&quot;C&quot;</span><span class="p">)</span>
  292. <span class="k">except</span> <span class="n">B</span><span class="p">:</span>
  293. <span class="nb">print</span><span class="p">(</span><span class="s2">&quot;B&quot;</span><span class="p">)</span>
  294. </pre></div>
  295. </div>
  296. <p>Note that if the <em>except clauses</em> were reversed (with <code class="docutils literal notranslate"><span class="pre">except</span> <span class="pre">B</span></code> first), it
  297. would have printed B, B, B — the first matching <em>except clause</em> is triggered.</p>
  298. <p>When an exception occurs, it may have associated values, also known as the
  299. exception’s <em>arguments</em>. The presence and types of the arguments depend on the
  300. exception type.</p>
  301. <p>The <em>except clause</em> may specify a variable after the exception name. The
  302. variable is bound to the exception instance which typically has an <code class="docutils literal notranslate"><span class="pre">args</span></code>
  303. attribute that stores the arguments. For convenience, builtin exception
  304. types define <a class="reference internal" href="../reference/datamodel.html#object.__str__" title="object.__str__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__str__()</span></code></a> to print all the arguments without explicitly
  305. accessing <code class="docutils literal notranslate"><span class="pre">.args</span></code>.</p>
  306. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="k">try</span><span class="p">:</span>
  307. <span class="gp">... </span> <span class="k">raise</span> <span class="ne">Exception</span><span class="p">(</span><span class="s1">&#39;spam&#39;</span><span class="p">,</span> <span class="s1">&#39;eggs&#39;</span><span class="p">)</span>
  308. <span class="gp">... </span><span class="k">except</span> <span class="ne">Exception</span> <span class="k">as</span> <span class="n">inst</span><span class="p">:</span>
  309. <span class="gp">... </span> <span class="nb">print</span><span class="p">(</span><span class="nb">type</span><span class="p">(</span><span class="n">inst</span><span class="p">))</span> <span class="c1"># the exception type</span>
  310. <span class="gp">... </span> <span class="nb">print</span><span class="p">(</span><span class="n">inst</span><span class="o">.</span><span class="n">args</span><span class="p">)</span> <span class="c1"># arguments stored in .args</span>
  311. <span class="gp">... </span> <span class="nb">print</span><span class="p">(</span><span class="n">inst</span><span class="p">)</span> <span class="c1"># __str__ allows args to be printed directly,</span>
  312. <span class="gp">... </span> <span class="c1"># but may be overridden in exception subclasses</span>
  313. <span class="gp">... </span> <span class="n">x</span><span class="p">,</span> <span class="n">y</span> <span class="o">=</span> <span class="n">inst</span><span class="o">.</span><span class="n">args</span> <span class="c1"># unpack args</span>
  314. <span class="gp">... </span> <span class="nb">print</span><span class="p">(</span><span class="s1">&#39;x =&#39;</span><span class="p">,</span> <span class="n">x</span><span class="p">)</span>
  315. <span class="gp">... </span> <span class="nb">print</span><span class="p">(</span><span class="s1">&#39;y =&#39;</span><span class="p">,</span> <span class="n">y</span><span class="p">)</span>
  316. <span class="gp">...</span>
  317. <span class="go">&lt;class &#39;Exception&#39;&gt;</span>
  318. <span class="go">(&#39;spam&#39;, &#39;eggs&#39;)</span>
  319. <span class="go">(&#39;spam&#39;, &#39;eggs&#39;)</span>
  320. <span class="go">x = spam</span>
  321. <span class="go">y = eggs</span>
  322. </pre></div>
  323. </div>
  324. <p>The exception’s <a class="reference internal" href="../reference/datamodel.html#object.__str__" title="object.__str__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__str__()</span></code></a> output is printed as the last part (‘detail’)
  325. of the message for unhandled exceptions.</p>
  326. <p><a class="reference internal" href="../library/exceptions.html#BaseException" title="BaseException"><code class="xref py py-exc docutils literal notranslate"><span class="pre">BaseException</span></code></a> is the common base class of all exceptions. One of its
  327. subclasses, <a class="reference internal" href="../library/exceptions.html#Exception" title="Exception"><code class="xref py py-exc docutils literal notranslate"><span class="pre">Exception</span></code></a>, is the base class of all the non-fatal exceptions.
  328. Exceptions which are not subclasses of <a class="reference internal" href="../library/exceptions.html#Exception" title="Exception"><code class="xref py py-exc docutils literal notranslate"><span class="pre">Exception</span></code></a> are not typically
  329. handled, because they are used to indicate that the program should terminate.
  330. They include <a class="reference internal" href="../library/exceptions.html#SystemExit" title="SystemExit"><code class="xref py py-exc docutils literal notranslate"><span class="pre">SystemExit</span></code></a> which is raised by <a class="reference internal" href="../library/sys.html#sys.exit" title="sys.exit"><code class="xref py py-meth docutils literal notranslate"><span class="pre">sys.exit()</span></code></a> and
  331. <a class="reference internal" href="../library/exceptions.html#KeyboardInterrupt" title="KeyboardInterrupt"><code class="xref py py-exc docutils literal notranslate"><span class="pre">KeyboardInterrupt</span></code></a> which is raised when a user wishes to interrupt
  332. the program.</p>
  333. <p><a class="reference internal" href="../library/exceptions.html#Exception" title="Exception"><code class="xref py py-exc docutils literal notranslate"><span class="pre">Exception</span></code></a> can be used as a wildcard that catches (almost) everything.
  334. However, it is good practice to be as specific as possible with the types
  335. of exceptions that we intend to handle, and to allow any unexpected
  336. exceptions to propagate on.</p>
  337. <p>The most common pattern for handling <a class="reference internal" href="../library/exceptions.html#Exception" title="Exception"><code class="xref py py-exc docutils literal notranslate"><span class="pre">Exception</span></code></a> is to print or log
  338. the exception and then re-raise it (allowing a caller to handle the
  339. exception as well):</p>
  340. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">sys</span>
  341. <span class="k">try</span><span class="p">:</span>
  342. <span class="n">f</span> <span class="o">=</span> <span class="nb">open</span><span class="p">(</span><span class="s1">&#39;myfile.txt&#39;</span><span class="p">)</span>
  343. <span class="n">s</span> <span class="o">=</span> <span class="n">f</span><span class="o">.</span><span class="n">readline</span><span class="p">()</span>
  344. <span class="n">i</span> <span class="o">=</span> <span class="nb">int</span><span class="p">(</span><span class="n">s</span><span class="o">.</span><span class="n">strip</span><span class="p">())</span>
  345. <span class="k">except</span> <span class="ne">OSError</span> <span class="k">as</span> <span class="n">err</span><span class="p">:</span>
  346. <span class="nb">print</span><span class="p">(</span><span class="s2">&quot;OS error:&quot;</span><span class="p">,</span> <span class="n">err</span><span class="p">)</span>
  347. <span class="k">except</span> <span class="ne">ValueError</span><span class="p">:</span>
  348. <span class="nb">print</span><span class="p">(</span><span class="s2">&quot;Could not convert data to an integer.&quot;</span><span class="p">)</span>
  349. <span class="k">except</span> <span class="ne">Exception</span> <span class="k">as</span> <span class="n">err</span><span class="p">:</span>
  350. <span class="nb">print</span><span class="p">(</span><span class="sa">f</span><span class="s2">&quot;Unexpected </span><span class="si">{</span><span class="n">err</span><span class="si">=}</span><span class="s2">, </span><span class="si">{</span><span class="nb">type</span><span class="p">(</span><span class="n">err</span><span class="p">)</span><span class="si">=}</span><span class="s2">&quot;</span><span class="p">)</span>
  351. <span class="k">raise</span>
  352. </pre></div>
  353. </div>
  354. <p>The <a class="reference internal" href="../reference/compound_stmts.html#try"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">try</span></code></a> … <a class="reference internal" href="../reference/compound_stmts.html#except"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">except</span></code></a> statement has an optional <em>else
  355. clause</em>, which, when present, must follow all <em>except clauses</em>. It is useful
  356. for code that must be executed if the <em>try clause</em> does not raise an exception.
  357. For example:</p>
  358. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">for</span> <span class="n">arg</span> <span class="ow">in</span> <span class="n">sys</span><span class="o">.</span><span class="n">argv</span><span class="p">[</span><span class="mi">1</span><span class="p">:]:</span>
  359. <span class="k">try</span><span class="p">:</span>
  360. <span class="n">f</span> <span class="o">=</span> <span class="nb">open</span><span class="p">(</span><span class="n">arg</span><span class="p">,</span> <span class="s1">&#39;r&#39;</span><span class="p">)</span>
  361. <span class="k">except</span> <span class="ne">OSError</span><span class="p">:</span>
  362. <span class="nb">print</span><span class="p">(</span><span class="s1">&#39;cannot open&#39;</span><span class="p">,</span> <span class="n">arg</span><span class="p">)</span>
  363. <span class="k">else</span><span class="p">:</span>
  364. <span class="nb">print</span><span class="p">(</span><span class="n">arg</span><span class="p">,</span> <span class="s1">&#39;has&#39;</span><span class="p">,</span> <span class="nb">len</span><span class="p">(</span><span class="n">f</span><span class="o">.</span><span class="n">readlines</span><span class="p">()),</span> <span class="s1">&#39;lines&#39;</span><span class="p">)</span>
  365. <span class="n">f</span><span class="o">.</span><span class="n">close</span><span class="p">()</span>
  366. </pre></div>
  367. </div>
  368. <p>The use of the <code class="xref std std-keyword docutils literal notranslate"><span class="pre">else</span></code> clause is better than adding additional code to
  369. the <a class="reference internal" href="../reference/compound_stmts.html#try"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">try</span></code></a> clause because it avoids accidentally catching an exception
  370. that wasn’t raised by the code being protected by the <code class="xref std std-keyword docutils literal notranslate"><span class="pre">try</span></code> …
  371. <code class="xref std std-keyword docutils literal notranslate"><span class="pre">except</span></code> statement.</p>
  372. <p>Exception handlers do not handle only exceptions that occur immediately in the
  373. <em>try clause</em>, but also those that occur inside functions that are called (even
  374. indirectly) in the <em>try clause</em>. For example:</p>
  375. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="k">def</span> <span class="nf">this_fails</span><span class="p">():</span>
  376. <span class="gp">... </span> <span class="n">x</span> <span class="o">=</span> <span class="mi">1</span><span class="o">/</span><span class="mi">0</span>
  377. <span class="gp">...</span>
  378. <span class="gp">&gt;&gt;&gt; </span><span class="k">try</span><span class="p">:</span>
  379. <span class="gp">... </span> <span class="n">this_fails</span><span class="p">()</span>
  380. <span class="gp">... </span><span class="k">except</span> <span class="ne">ZeroDivisionError</span> <span class="k">as</span> <span class="n">err</span><span class="p">:</span>
  381. <span class="gp">... </span> <span class="nb">print</span><span class="p">(</span><span class="s1">&#39;Handling run-time error:&#39;</span><span class="p">,</span> <span class="n">err</span><span class="p">)</span>
  382. <span class="gp">...</span>
  383. <span class="go">Handling run-time error: division by zero</span>
  384. </pre></div>
  385. </div>
  386. </section>
  387. <section id="raising-exceptions">
  388. <span id="tut-raising"></span><h2><span class="section-number">8.4. </span>Raising Exceptions<a class="headerlink" href="#raising-exceptions" title="Permalink to this headline">¶</a></h2>
  389. <p>The <a class="reference internal" href="../reference/simple_stmts.html#raise"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">raise</span></code></a> statement allows the programmer to force a specified
  390. exception to occur. For example:</p>
  391. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="k">raise</span> <span class="ne">NameError</span><span class="p">(</span><span class="s1">&#39;HiThere&#39;</span><span class="p">)</span>
  392. <span class="gt">Traceback (most recent call last):</span>
  393. File <span class="nb">&quot;&lt;stdin&gt;&quot;</span>, line <span class="m">1</span>, in <span class="n">&lt;module&gt;</span>
  394. <span class="gr">NameError</span>: <span class="n">HiThere</span>
  395. </pre></div>
  396. </div>
  397. <p>The sole argument to <a class="reference internal" href="../reference/simple_stmts.html#raise"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">raise</span></code></a> indicates the exception to be raised.
  398. This must be either an exception instance or an exception class (a class that
  399. derives from <a class="reference internal" href="../library/exceptions.html#BaseException" title="BaseException"><code class="xref py py-class docutils literal notranslate"><span class="pre">BaseException</span></code></a>, such as <a class="reference internal" href="../library/exceptions.html#Exception" title="Exception"><code class="xref py py-exc docutils literal notranslate"><span class="pre">Exception</span></code></a> or one of its
  400. subclasses). If an exception class is passed, it will be implicitly
  401. instantiated by calling its constructor with no arguments:</p>
  402. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">raise</span> <span class="ne">ValueError</span> <span class="c1"># shorthand for &#39;raise ValueError()&#39;</span>
  403. </pre></div>
  404. </div>
  405. <p>If you need to determine whether an exception was raised but don’t intend to
  406. handle it, a simpler form of the <a class="reference internal" href="../reference/simple_stmts.html#raise"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">raise</span></code></a> statement allows you to
  407. re-raise the exception:</p>
  408. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="k">try</span><span class="p">:</span>
  409. <span class="gp">... </span> <span class="k">raise</span> <span class="ne">NameError</span><span class="p">(</span><span class="s1">&#39;HiThere&#39;</span><span class="p">)</span>
  410. <span class="gp">... </span><span class="k">except</span> <span class="ne">NameError</span><span class="p">:</span>
  411. <span class="gp">... </span> <span class="nb">print</span><span class="p">(</span><span class="s1">&#39;An exception flew by!&#39;</span><span class="p">)</span>
  412. <span class="gp">... </span> <span class="k">raise</span>
  413. <span class="gp">...</span>
  414. <span class="go">An exception flew by!</span>
  415. <span class="gt">Traceback (most recent call last):</span>
  416. File <span class="nb">&quot;&lt;stdin&gt;&quot;</span>, line <span class="m">2</span>, in <span class="n">&lt;module&gt;</span>
  417. <span class="gr">NameError</span>: <span class="n">HiThere</span>
  418. </pre></div>
  419. </div>
  420. </section>
  421. <section id="exception-chaining">
  422. <span id="tut-exception-chaining"></span><h2><span class="section-number">8.5. </span>Exception Chaining<a class="headerlink" href="#exception-chaining" title="Permalink to this headline">¶</a></h2>
  423. <p>If an unhandled exception occurs inside an <a class="reference internal" href="../reference/compound_stmts.html#except"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">except</span></code></a> section, it will
  424. have the exception being handled attached to it and included in the error
  425. message:</p>
  426. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="k">try</span><span class="p">:</span>
  427. <span class="gp">... </span> <span class="nb">open</span><span class="p">(</span><span class="s2">&quot;database.sqlite&quot;</span><span class="p">)</span>
  428. <span class="gp">... </span><span class="k">except</span> <span class="ne">OSError</span><span class="p">:</span>
  429. <span class="gp">... </span> <span class="k">raise</span> <span class="ne">RuntimeError</span><span class="p">(</span><span class="s2">&quot;unable to handle error&quot;</span><span class="p">)</span>
  430. <span class="gp">...</span>
  431. <span class="gt">Traceback (most recent call last):</span>
  432. File <span class="nb">&quot;&lt;stdin&gt;&quot;</span>, line <span class="m">2</span>, in <span class="n">&lt;module&gt;</span>
  433. <span class="gr">FileNotFoundError</span>: <span class="n">[Errno 2] No such file or directory: &#39;database.sqlite&#39;</span>
  434. <span class="gt">During handling of the above exception, another exception occurred:</span>
  435. <span class="gt">Traceback (most recent call last):</span>
  436. File <span class="nb">&quot;&lt;stdin&gt;&quot;</span>, line <span class="m">4</span>, in <span class="n">&lt;module&gt;</span>
  437. <span class="gr">RuntimeError</span>: <span class="n">unable to handle error</span>
  438. </pre></div>
  439. </div>
  440. <p>To indicate that an exception is a direct consequence of another, the
  441. <a class="reference internal" href="../reference/simple_stmts.html#raise"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">raise</span></code></a> statement allows an optional <a class="reference internal" href="../reference/simple_stmts.html#raise"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">from</span></code></a> clause:</p>
  442. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="c1"># exc must be exception instance or None.</span>
  443. <span class="k">raise</span> <span class="ne">RuntimeError</span> <span class="kn">from</span> <span class="nn">exc</span>
  444. </pre></div>
  445. </div>
  446. <p>This can be useful when you are transforming exceptions. For example:</p>
  447. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="k">def</span> <span class="nf">func</span><span class="p">():</span>
  448. <span class="gp">... </span> <span class="k">raise</span> <span class="ne">ConnectionError</span>
  449. <span class="gp">...</span>
  450. <span class="gp">&gt;&gt;&gt; </span><span class="k">try</span><span class="p">:</span>
  451. <span class="gp">... </span> <span class="n">func</span><span class="p">()</span>
  452. <span class="gp">... </span><span class="k">except</span> <span class="ne">ConnectionError</span> <span class="k">as</span> <span class="n">exc</span><span class="p">:</span>
  453. <span class="gp">... </span> <span class="k">raise</span> <span class="ne">RuntimeError</span><span class="p">(</span><span class="s1">&#39;Failed to open database&#39;</span><span class="p">)</span> <span class="kn">from</span> <span class="nn">exc</span>
  454. <span class="gp">...</span>
  455. <span class="gt">Traceback (most recent call last):</span>
  456. File <span class="nb">&quot;&lt;stdin&gt;&quot;</span>, line <span class="m">2</span>, in <span class="n">&lt;module&gt;</span>
  457. File <span class="nb">&quot;&lt;stdin&gt;&quot;</span>, line <span class="m">2</span>, in <span class="n">func</span>
  458. <span class="gr">ConnectionError</span>
  459. <span class="gt">The above exception was the direct cause of the following exception:</span>
  460. <span class="gt">Traceback (most recent call last):</span>
  461. File <span class="nb">&quot;&lt;stdin&gt;&quot;</span>, line <span class="m">4</span>, in <span class="n">&lt;module&gt;</span>
  462. <span class="gr">RuntimeError</span>: <span class="n">Failed to open database</span>
  463. </pre></div>
  464. </div>
  465. <p>It also allows disabling automatic exception chaining using the <code class="docutils literal notranslate"><span class="pre">from</span> <span class="pre">None</span></code>
  466. idiom:</p>
  467. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="k">try</span><span class="p">:</span>
  468. <span class="gp">... </span> <span class="nb">open</span><span class="p">(</span><span class="s1">&#39;database.sqlite&#39;</span><span class="p">)</span>
  469. <span class="gp">... </span><span class="k">except</span> <span class="ne">OSError</span><span class="p">:</span>
  470. <span class="gp">... </span> <span class="k">raise</span> <span class="ne">RuntimeError</span> <span class="kn">from</span> <span class="kc">None</span>
  471. <span class="gp">...</span>
  472. <span class="gt">Traceback (most recent call last):</span>
  473. File <span class="nb">&quot;&lt;stdin&gt;&quot;</span>, line <span class="m">4</span>, in <span class="n">&lt;module&gt;</span>
  474. <span class="gr">RuntimeError</span>
  475. </pre></div>
  476. </div>
  477. <p>For more information about chaining mechanics, see <a class="reference internal" href="../library/exceptions.html#bltin-exceptions"><span class="std std-ref">Built-in Exceptions</span></a>.</p>
  478. </section>
  479. <section id="user-defined-exceptions">
  480. <span id="tut-userexceptions"></span><h2><span class="section-number">8.6. </span>User-defined Exceptions<a class="headerlink" href="#user-defined-exceptions" title="Permalink to this headline">¶</a></h2>
  481. <p>Programs may name their own exceptions by creating a new exception class (see
  482. <a class="reference internal" href="classes.html#tut-classes"><span class="std std-ref">Classes</span></a> for more about Python classes). Exceptions should typically
  483. be derived from the <a class="reference internal" href="../library/exceptions.html#Exception" title="Exception"><code class="xref py py-exc docutils literal notranslate"><span class="pre">Exception</span></code></a> class, either directly or indirectly.</p>
  484. <p>Exception classes can be defined which do anything any other class can do, but
  485. are usually kept simple, often only offering a number of attributes that allow
  486. information about the error to be extracted by handlers for the exception.</p>
  487. <p>Most exceptions are defined with names that end in “Error”, similar to the
  488. naming of the standard exceptions.</p>
  489. <p>Many standard modules define their own exceptions to report errors that may
  490. occur in functions they define.</p>
  491. </section>
  492. <section id="defining-clean-up-actions">
  493. <span id="tut-cleanup"></span><h2><span class="section-number">8.7. </span>Defining Clean-up Actions<a class="headerlink" href="#defining-clean-up-actions" title="Permalink to this headline">¶</a></h2>
  494. <p>The <a class="reference internal" href="../reference/compound_stmts.html#try"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">try</span></code></a> statement has another optional clause which is intended to
  495. define clean-up actions that must be executed under all circumstances. For
  496. example:</p>
  497. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="k">try</span><span class="p">:</span>
  498. <span class="gp">... </span> <span class="k">raise</span> <span class="ne">KeyboardInterrupt</span>
  499. <span class="gp">... </span><span class="k">finally</span><span class="p">:</span>
  500. <span class="gp">... </span> <span class="nb">print</span><span class="p">(</span><span class="s1">&#39;Goodbye, world!&#39;</span><span class="p">)</span>
  501. <span class="gp">...</span>
  502. <span class="go">Goodbye, world!</span>
  503. <span class="gt">Traceback (most recent call last):</span>
  504. File <span class="nb">&quot;&lt;stdin&gt;&quot;</span>, line <span class="m">2</span>, in <span class="n">&lt;module&gt;</span>
  505. <span class="nc">KeyboardInterrupt</span>
  506. </pre></div>
  507. </div>
  508. <p>If a <a class="reference internal" href="../reference/compound_stmts.html#finally"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">finally</span></code></a> clause is present, the <code class="xref std std-keyword docutils literal notranslate"><span class="pre">finally</span></code>
  509. clause will execute as the last task before the <a class="reference internal" href="../reference/compound_stmts.html#try"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">try</span></code></a>
  510. statement completes. The <code class="xref std std-keyword docutils literal notranslate"><span class="pre">finally</span></code> clause runs whether or
  511. not the <code class="xref std std-keyword docutils literal notranslate"><span class="pre">try</span></code> statement produces an exception. The following
  512. points discuss more complex cases when an exception occurs:</p>
  513. <ul class="simple">
  514. <li><p>If an exception occurs during execution of the <code class="xref std std-keyword docutils literal notranslate"><span class="pre">try</span></code>
  515. clause, the exception may be handled by an <a class="reference internal" href="../reference/compound_stmts.html#except"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">except</span></code></a>
  516. clause. If the exception is not handled by an <code class="xref std std-keyword docutils literal notranslate"><span class="pre">except</span></code>
  517. clause, the exception is re-raised after the <code class="xref std std-keyword docutils literal notranslate"><span class="pre">finally</span></code>
  518. clause has been executed.</p></li>
  519. <li><p>An exception could occur during execution of an <code class="xref std std-keyword docutils literal notranslate"><span class="pre">except</span></code>
  520. or <code class="xref std std-keyword docutils literal notranslate"><span class="pre">else</span></code> clause. Again, the exception is re-raised after
  521. the <code class="xref std std-keyword docutils literal notranslate"><span class="pre">finally</span></code> clause has been executed.</p></li>
  522. <li><p>If the <code class="xref std std-keyword docutils literal notranslate"><span class="pre">finally</span></code> clause executes a <a class="reference internal" href="../reference/simple_stmts.html#break"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">break</span></code></a>,
  523. <a class="reference internal" href="../reference/simple_stmts.html#continue"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">continue</span></code></a> or <a class="reference internal" href="../reference/simple_stmts.html#return"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">return</span></code></a> statement, exceptions are not
  524. re-raised.</p></li>
  525. <li><p>If the <code class="xref std std-keyword docutils literal notranslate"><span class="pre">try</span></code> statement reaches a <a class="reference internal" href="../reference/simple_stmts.html#break"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">break</span></code></a>,
  526. <a class="reference internal" href="../reference/simple_stmts.html#continue"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">continue</span></code></a> or <a class="reference internal" href="../reference/simple_stmts.html#return"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">return</span></code></a> statement, the
  527. <code class="xref std std-keyword docutils literal notranslate"><span class="pre">finally</span></code> clause will execute just prior to the
  528. <code class="xref std std-keyword docutils literal notranslate"><span class="pre">break</span></code>, <code class="xref std std-keyword docutils literal notranslate"><span class="pre">continue</span></code> or <code class="xref std std-keyword docutils literal notranslate"><span class="pre">return</span></code>
  529. statement’s execution.</p></li>
  530. <li><p>If a <code class="xref std std-keyword docutils literal notranslate"><span class="pre">finally</span></code> clause includes a <code class="xref std std-keyword docutils literal notranslate"><span class="pre">return</span></code>
  531. statement, the returned value will be the one from the
  532. <code class="xref std std-keyword docutils literal notranslate"><span class="pre">finally</span></code> clause’s <code class="xref std std-keyword docutils literal notranslate"><span class="pre">return</span></code> statement, not the
  533. value from the <code class="xref std std-keyword docutils literal notranslate"><span class="pre">try</span></code> clause’s <code class="xref std std-keyword docutils literal notranslate"><span class="pre">return</span></code>
  534. statement.</p></li>
  535. </ul>
  536. <p>For example:</p>
  537. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="k">def</span> <span class="nf">bool_return</span><span class="p">():</span>
  538. <span class="gp">... </span> <span class="k">try</span><span class="p">:</span>
  539. <span class="gp">... </span> <span class="k">return</span> <span class="kc">True</span>
  540. <span class="gp">... </span> <span class="k">finally</span><span class="p">:</span>
  541. <span class="gp">... </span> <span class="k">return</span> <span class="kc">False</span>
  542. <span class="gp">...</span>
  543. <span class="gp">&gt;&gt;&gt; </span><span class="n">bool_return</span><span class="p">()</span>
  544. <span class="go">False</span>
  545. </pre></div>
  546. </div>
  547. <p>A more complicated example:</p>
  548. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="k">def</span> <span class="nf">divide</span><span class="p">(</span><span class="n">x</span><span class="p">,</span> <span class="n">y</span><span class="p">):</span>
  549. <span class="gp">... </span> <span class="k">try</span><span class="p">:</span>
  550. <span class="gp">... </span> <span class="n">result</span> <span class="o">=</span> <span class="n">x</span> <span class="o">/</span> <span class="n">y</span>
  551. <span class="gp">... </span> <span class="k">except</span> <span class="ne">ZeroDivisionError</span><span class="p">:</span>
  552. <span class="gp">... </span> <span class="nb">print</span><span class="p">(</span><span class="s2">&quot;division by zero!&quot;</span><span class="p">)</span>
  553. <span class="gp">... </span> <span class="k">else</span><span class="p">:</span>
  554. <span class="gp">... </span> <span class="nb">print</span><span class="p">(</span><span class="s2">&quot;result is&quot;</span><span class="p">,</span> <span class="n">result</span><span class="p">)</span>
  555. <span class="gp">... </span> <span class="k">finally</span><span class="p">:</span>
  556. <span class="gp">... </span> <span class="nb">print</span><span class="p">(</span><span class="s2">&quot;executing finally clause&quot;</span><span class="p">)</span>
  557. <span class="gp">...</span>
  558. <span class="gp">&gt;&gt;&gt; </span><span class="n">divide</span><span class="p">(</span><span class="mi">2</span><span class="p">,</span> <span class="mi">1</span><span class="p">)</span>
  559. <span class="go">result is 2.0</span>
  560. <span class="go">executing finally clause</span>
  561. <span class="gp">&gt;&gt;&gt; </span><span class="n">divide</span><span class="p">(</span><span class="mi">2</span><span class="p">,</span> <span class="mi">0</span><span class="p">)</span>
  562. <span class="go">division by zero!</span>
  563. <span class="go">executing finally clause</span>
  564. <span class="gp">&gt;&gt;&gt; </span><span class="n">divide</span><span class="p">(</span><span class="s2">&quot;2&quot;</span><span class="p">,</span> <span class="s2">&quot;1&quot;</span><span class="p">)</span>
  565. <span class="go">executing finally clause</span>
  566. <span class="gt">Traceback (most recent call last):</span>
  567. File <span class="nb">&quot;&lt;stdin&gt;&quot;</span>, line <span class="m">1</span>, in <span class="n">&lt;module&gt;</span>
  568. File <span class="nb">&quot;&lt;stdin&gt;&quot;</span>, line <span class="m">3</span>, in <span class="n">divide</span>
  569. <span class="gr">TypeError</span>: <span class="n">unsupported operand type(s) for /: &#39;str&#39; and &#39;str&#39;</span>
  570. </pre></div>
  571. </div>
  572. <p>As you can see, the <a class="reference internal" href="../reference/compound_stmts.html#finally"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">finally</span></code></a> clause is executed in any event. The
  573. <a class="reference internal" href="../library/exceptions.html#TypeError" title="TypeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">TypeError</span></code></a> raised by dividing two strings is not handled by the
  574. <a class="reference internal" href="../reference/compound_stmts.html#except"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">except</span></code></a> clause and therefore re-raised after the <code class="xref std std-keyword docutils literal notranslate"><span class="pre">finally</span></code>
  575. clause has been executed.</p>
  576. <p>In real world applications, the <a class="reference internal" href="../reference/compound_stmts.html#finally"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">finally</span></code></a> clause is useful for
  577. releasing external resources (such as files or network connections), regardless
  578. of whether the use of the resource was successful.</p>
  579. </section>
  580. <section id="predefined-clean-up-actions">
  581. <span id="tut-cleanup-with"></span><h2><span class="section-number">8.8. </span>Predefined Clean-up Actions<a class="headerlink" href="#predefined-clean-up-actions" title="Permalink to this headline">¶</a></h2>
  582. <p>Some objects define standard clean-up actions to be undertaken when the object
  583. is no longer needed, regardless of whether or not the operation using the object
  584. succeeded or failed. Look at the following example, which tries to open a file
  585. and print its contents to the screen.</p>
  586. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">for</span> <span class="n">line</span> <span class="ow">in</span> <span class="nb">open</span><span class="p">(</span><span class="s2">&quot;myfile.txt&quot;</span><span class="p">):</span>
  587. <span class="nb">print</span><span class="p">(</span><span class="n">line</span><span class="p">,</span> <span class="n">end</span><span class="o">=</span><span class="s2">&quot;&quot;</span><span class="p">)</span>
  588. </pre></div>
  589. </div>
  590. <p>The problem with this code is that it leaves the file open for an indeterminate
  591. amount of time after this part of the code has finished executing.
  592. This is not an issue in simple scripts, but can be a problem for larger
  593. applications. The <a class="reference internal" href="../reference/compound_stmts.html#with"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">with</span></code></a> statement allows objects like files to be
  594. used in a way that ensures they are always cleaned up promptly and correctly.</p>
  595. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">with</span> <span class="nb">open</span><span class="p">(</span><span class="s2">&quot;myfile.txt&quot;</span><span class="p">)</span> <span class="k">as</span> <span class="n">f</span><span class="p">:</span>
  596. <span class="k">for</span> <span class="n">line</span> <span class="ow">in</span> <span class="n">f</span><span class="p">:</span>
  597. <span class="nb">print</span><span class="p">(</span><span class="n">line</span><span class="p">,</span> <span class="n">end</span><span class="o">=</span><span class="s2">&quot;&quot;</span><span class="p">)</span>
  598. </pre></div>
  599. </div>
  600. <p>After the statement is executed, the file <em>f</em> is always closed, even if a
  601. problem was encountered while processing the lines. Objects which, like files,
  602. provide predefined clean-up actions will indicate this in their documentation.</p>
  603. </section>
  604. <section id="raising-and-handling-multiple-unrelated-exceptions">
  605. <span id="tut-exception-groups"></span><h2><span class="section-number">8.9. </span>Raising and Handling Multiple Unrelated Exceptions<a class="headerlink" href="#raising-and-handling-multiple-unrelated-exceptions" title="Permalink to this headline">¶</a></h2>
  606. <p>There are situations where it is necessary to report several exceptions that
  607. have occurred. This is often the case in concurrency frameworks, when several
  608. tasks may have failed in parallel, but there are also other use cases where
  609. it is desirable to continue execution and collect multiple errors rather than
  610. raise the first exception.</p>
  611. <p>The builtin <a class="reference internal" href="../library/exceptions.html#ExceptionGroup" title="ExceptionGroup"><code class="xref py py-exc docutils literal notranslate"><span class="pre">ExceptionGroup</span></code></a> wraps a list of exception instances so
  612. that they can be raised together. It is an exception itself, so it can be
  613. caught like any other exception.</p>
  614. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="k">def</span> <span class="nf">f</span><span class="p">():</span>
  615. <span class="gp">... </span> <span class="n">excs</span> <span class="o">=</span> <span class="p">[</span><span class="ne">OSError</span><span class="p">(</span><span class="s1">&#39;error 1&#39;</span><span class="p">),</span> <span class="ne">SystemError</span><span class="p">(</span><span class="s1">&#39;error 2&#39;</span><span class="p">)]</span>
  616. <span class="gp">... </span> <span class="k">raise</span> <span class="n">ExceptionGroup</span><span class="p">(</span><span class="s1">&#39;there were problems&#39;</span><span class="p">,</span> <span class="n">excs</span><span class="p">)</span>
  617. <span class="gp">...</span>
  618. <span class="gp">&gt;&gt;&gt; </span><span class="n">f</span><span class="p">()</span>
  619. <span class="go"> + Exception Group Traceback (most recent call last):</span>
  620. <span class="go"> | File &quot;&lt;stdin&gt;&quot;, line 1, in &lt;module&gt;</span>
  621. <span class="go"> | File &quot;&lt;stdin&gt;&quot;, line 3, in f</span>
  622. <span class="go"> | ExceptionGroup: there were problems</span>
  623. <span class="go"> +-+---------------- 1 ----------------</span>
  624. <span class="go"> | OSError: error 1</span>
  625. <span class="go"> +---------------- 2 ----------------</span>
  626. <span class="go"> | SystemError: error 2</span>
  627. <span class="go"> +------------------------------------</span>
  628. <span class="gp">&gt;&gt;&gt; </span><span class="k">try</span><span class="p">:</span>
  629. <span class="gp">... </span> <span class="n">f</span><span class="p">()</span>
  630. <span class="gp">... </span><span class="k">except</span> <span class="ne">Exception</span> <span class="k">as</span> <span class="n">e</span><span class="p">:</span>
  631. <span class="gp">... </span> <span class="nb">print</span><span class="p">(</span><span class="sa">f</span><span class="s1">&#39;caught </span><span class="si">{</span><span class="nb">type</span><span class="p">(</span><span class="n">e</span><span class="p">)</span><span class="si">}</span><span class="s1">: e&#39;</span><span class="p">)</span>
  632. <span class="gp">...</span>
  633. <span class="go">caught &lt;class &#39;ExceptionGroup&#39;&gt;: e</span>
  634. <span class="gp">&gt;&gt;&gt;</span>
  635. </pre></div>
  636. </div>
  637. <p>By using <code class="docutils literal notranslate"><span class="pre">except*</span></code> instead of <code class="docutils literal notranslate"><span class="pre">except</span></code>, we can selectively
  638. handle only the exceptions in the group that match a certain
  639. type. In the following example, which shows a nested exception
  640. group, each <code class="docutils literal notranslate"><span class="pre">except*</span></code> clause extracts from the group exceptions
  641. of a certain type while letting all other exceptions propagate to
  642. other clauses and eventually to be reraised.</p>
  643. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="k">def</span> <span class="nf">f</span><span class="p">():</span>
  644. <span class="gp">... </span> <span class="k">raise</span> <span class="n">ExceptionGroup</span><span class="p">(</span>
  645. <span class="gp">... </span> <span class="s2">&quot;group1&quot;</span><span class="p">,</span>
  646. <span class="gp">... </span> <span class="p">[</span>
  647. <span class="gp">... </span> <span class="ne">OSError</span><span class="p">(</span><span class="mi">1</span><span class="p">),</span>
  648. <span class="gp">... </span> <span class="ne">SystemError</span><span class="p">(</span><span class="mi">2</span><span class="p">),</span>
  649. <span class="gp">... </span> <span class="n">ExceptionGroup</span><span class="p">(</span>
  650. <span class="gp">... </span> <span class="s2">&quot;group2&quot;</span><span class="p">,</span>
  651. <span class="gp">... </span> <span class="p">[</span>
  652. <span class="gp">... </span> <span class="ne">OSError</span><span class="p">(</span><span class="mi">3</span><span class="p">),</span>
  653. <span class="gp">... </span> <span class="ne">RecursionError</span><span class="p">(</span><span class="mi">4</span><span class="p">)</span>
  654. <span class="gp">... </span> <span class="p">]</span>
  655. <span class="gp">... </span> <span class="p">)</span>
  656. <span class="gp">... </span> <span class="p">]</span>
  657. <span class="gp">... </span> <span class="p">)</span>
  658. <span class="gp">...</span>
  659. <span class="gp">&gt;&gt;&gt; </span><span class="k">try</span><span class="p">:</span>
  660. <span class="gp">... </span> <span class="n">f</span><span class="p">()</span>
  661. <span class="gp">... </span><span class="k">except</span><span class="o">*</span> <span class="ne">OSError</span> <span class="k">as</span> <span class="n">e</span><span class="p">:</span>
  662. <span class="gp">... </span> <span class="nb">print</span><span class="p">(</span><span class="s2">&quot;There were OSErrors&quot;</span><span class="p">)</span>
  663. <span class="gp">... </span><span class="k">except</span><span class="o">*</span> <span class="ne">SystemError</span> <span class="k">as</span> <span class="n">e</span><span class="p">:</span>
  664. <span class="gp">... </span> <span class="nb">print</span><span class="p">(</span><span class="s2">&quot;There were SystemErrors&quot;</span><span class="p">)</span>
  665. <span class="gp">...</span>
  666. <span class="go">There were OSErrors</span>
  667. <span class="go">There were SystemErrors</span>
  668. <span class="go"> + Exception Group Traceback (most recent call last):</span>
  669. <span class="go"> | File &quot;&lt;stdin&gt;&quot;, line 2, in &lt;module&gt;</span>
  670. <span class="go"> | File &quot;&lt;stdin&gt;&quot;, line 2, in f</span>
  671. <span class="go"> | ExceptionGroup: group1</span>
  672. <span class="go"> +-+---------------- 1 ----------------</span>
  673. <span class="go"> | ExceptionGroup: group2</span>
  674. <span class="go"> +-+---------------- 1 ----------------</span>
  675. <span class="go"> | RecursionError: 4</span>
  676. <span class="go"> +------------------------------------</span>
  677. <span class="gp">&gt;&gt;&gt;</span>
  678. </pre></div>
  679. </div>
  680. <p>Note that the exceptions nested in an exception group must be instances,
  681. not types. This is because in practice the exceptions would typically
  682. be ones that have already been raised and caught by the program, along
  683. the following pattern:</p>
  684. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">excs</span> <span class="o">=</span> <span class="p">[]</span>
  685. <span class="gp">... </span><span class="k">for</span> <span class="n">test</span> <span class="ow">in</span> <span class="n">tests</span><span class="p">:</span>
  686. <span class="gp">... </span> <span class="k">try</span><span class="p">:</span>
  687. <span class="gp">... </span> <span class="n">test</span><span class="o">.</span><span class="n">run</span><span class="p">()</span>
  688. <span class="gp">... </span> <span class="k">except</span> <span class="ne">Exception</span> <span class="k">as</span> <span class="n">e</span><span class="p">:</span>
  689. <span class="gp">... </span> <span class="n">excs</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="n">e</span><span class="p">)</span>
  690. <span class="gp">...</span>
  691. <span class="gp">&gt;&gt;&gt; </span><span class="k">if</span> <span class="n">excs</span><span class="p">:</span>
  692. <span class="gp">... </span> <span class="k">raise</span> <span class="n">ExceptionGroup</span><span class="p">(</span><span class="s2">&quot;Test Failures&quot;</span><span class="p">,</span> <span class="n">excs</span><span class="p">)</span>
  693. <span class="gp">...</span>
  694. </pre></div>
  695. </div>
  696. </section>
  697. <section id="enriching-exceptions-with-notes">
  698. <span id="tut-exception-notes"></span><h2><span class="section-number">8.10. </span>Enriching Exceptions with Notes<a class="headerlink" href="#enriching-exceptions-with-notes" title="Permalink to this headline">¶</a></h2>
  699. <p>When an exception is created in order to be raised, it is usually initialized
  700. with information that describes the error that has occurred. There are cases
  701. where it is useful to add information after the exception was caught. For this
  702. purpose, exceptions have a method <code class="docutils literal notranslate"><span class="pre">add_note(note)</span></code> that accepts a string and
  703. adds it to the exception’s notes list. The standard traceback rendering
  704. includes all notes, in the order they were added, after the exception.</p>
  705. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="k">try</span><span class="p">:</span>
  706. <span class="gp">... </span> <span class="k">raise</span> <span class="ne">TypeError</span><span class="p">(</span><span class="s1">&#39;bad type&#39;</span><span class="p">)</span>
  707. <span class="gp">... </span><span class="k">except</span> <span class="ne">Exception</span> <span class="k">as</span> <span class="n">e</span><span class="p">:</span>
  708. <span class="gp">... </span> <span class="n">e</span><span class="o">.</span><span class="n">add_note</span><span class="p">(</span><span class="s1">&#39;Add some information&#39;</span><span class="p">)</span>
  709. <span class="gp">... </span> <span class="n">e</span><span class="o">.</span><span class="n">add_note</span><span class="p">(</span><span class="s1">&#39;Add some more information&#39;</span><span class="p">)</span>
  710. <span class="gp">... </span> <span class="k">raise</span>
  711. <span class="gp">...</span>
  712. <span class="gt">Traceback (most recent call last):</span>
  713. File <span class="nb">&quot;&lt;stdin&gt;&quot;</span>, line <span class="m">2</span>, in <span class="n">&lt;module&gt;</span>
  714. <span class="gr">TypeError</span>: <span class="n">bad type</span>
  715. <span class="x">Add some information</span>
  716. <span class="x">Add some more information</span>
  717. <span class="gp">&gt;&gt;&gt;</span>
  718. </pre></div>
  719. </div>
  720. <p>For example, when collecting exceptions into an exception group, we may want
  721. to add context information for the individual errors. In the following each
  722. exception in the group has a note indicating when this error has occurred.</p>
  723. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="k">def</span> <span class="nf">f</span><span class="p">():</span>
  724. <span class="gp">... </span> <span class="k">raise</span> <span class="ne">OSError</span><span class="p">(</span><span class="s1">&#39;operation failed&#39;</span><span class="p">)</span>
  725. <span class="gp">...</span>
  726. <span class="gp">&gt;&gt;&gt; </span><span class="n">excs</span> <span class="o">=</span> <span class="p">[]</span>
  727. <span class="gp">&gt;&gt;&gt; </span><span class="k">for</span> <span class="n">i</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="mi">3</span><span class="p">):</span>
  728. <span class="gp">... </span> <span class="k">try</span><span class="p">:</span>
  729. <span class="gp">... </span> <span class="n">f</span><span class="p">()</span>
  730. <span class="gp">... </span> <span class="k">except</span> <span class="ne">Exception</span> <span class="k">as</span> <span class="n">e</span><span class="p">:</span>
  731. <span class="gp">... </span> <span class="n">e</span><span class="o">.</span><span class="n">add_note</span><span class="p">(</span><span class="sa">f</span><span class="s1">&#39;Happened in Iteration </span><span class="si">{</span><span class="n">i</span><span class="o">+</span><span class="mi">1</span><span class="si">}</span><span class="s1">&#39;</span><span class="p">)</span>
  732. <span class="gp">... </span> <span class="n">excs</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="n">e</span><span class="p">)</span>
  733. <span class="gp">...</span>
  734. <span class="gp">&gt;&gt;&gt; </span><span class="k">raise</span> <span class="n">ExceptionGroup</span><span class="p">(</span><span class="s1">&#39;We have some problems&#39;</span><span class="p">,</span> <span class="n">excs</span><span class="p">)</span>
  735. <span class="go"> + Exception Group Traceback (most recent call last):</span>
  736. <span class="go"> | File &quot;&lt;stdin&gt;&quot;, line 1, in &lt;module&gt;</span>
  737. <span class="go"> | ExceptionGroup: We have some problems (3 sub-exceptions)</span>
  738. <span class="go"> +-+---------------- 1 ----------------</span>
  739. <span class="go"> | Traceback (most recent call last):</span>
  740. <span class="go"> | File &quot;&lt;stdin&gt;&quot;, line 3, in &lt;module&gt;</span>
  741. <span class="go"> | File &quot;&lt;stdin&gt;&quot;, line 2, in f</span>
  742. <span class="go"> | OSError: operation failed</span>
  743. <span class="go"> | Happened in Iteration 1</span>
  744. <span class="go"> +---------------- 2 ----------------</span>
  745. <span class="go"> | Traceback (most recent call last):</span>
  746. <span class="go"> | File &quot;&lt;stdin&gt;&quot;, line 3, in &lt;module&gt;</span>
  747. <span class="go"> | File &quot;&lt;stdin&gt;&quot;, line 2, in f</span>
  748. <span class="go"> | OSError: operation failed</span>
  749. <span class="go"> | Happened in Iteration 2</span>
  750. <span class="go"> +---------------- 3 ----------------</span>
  751. <span class="go"> | Traceback (most recent call last):</span>
  752. <span class="go"> | File &quot;&lt;stdin&gt;&quot;, line 3, in &lt;module&gt;</span>
  753. <span class="go"> | File &quot;&lt;stdin&gt;&quot;, line 2, in f</span>
  754. <span class="go"> | OSError: operation failed</span>
  755. <span class="go"> | Happened in Iteration 3</span>
  756. <span class="go"> +------------------------------------</span>
  757. <span class="gp">&gt;&gt;&gt;</span>
  758. </pre></div>
  759. </div>
  760. </section>
  761. </section>
  762. <div class="clearer"></div>
  763. </div>
  764. </div>
  765. </div>
  766. <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
  767. <div class="sphinxsidebarwrapper">
  768. <div>
  769. <h3><a href="../contents.html">Table of Contents</a></h3>
  770. <ul>
  771. <li><a class="reference internal" href="#">8. Errors and Exceptions</a><ul>
  772. <li><a class="reference internal" href="#syntax-errors">8.1. Syntax Errors</a></li>
  773. <li><a class="reference internal" href="#exceptions">8.2. Exceptions</a></li>
  774. <li><a class="reference internal" href="#handling-exceptions">8.3. Handling Exceptions</a></li>
  775. <li><a class="reference internal" href="#raising-exceptions">8.4. Raising Exceptions</a></li>
  776. <li><a class="reference internal" href="#exception-chaining">8.5. Exception Chaining</a></li>
  777. <li><a class="reference internal" href="#user-defined-exceptions">8.6. User-defined Exceptions</a></li>
  778. <li><a class="reference internal" href="#defining-clean-up-actions">8.7. Defining Clean-up Actions</a></li>
  779. <li><a class="reference internal" href="#predefined-clean-up-actions">8.8. Predefined Clean-up Actions</a></li>
  780. <li><a class="reference internal" href="#raising-and-handling-multiple-unrelated-exceptions">8.9. Raising and Handling Multiple Unrelated Exceptions</a></li>
  781. <li><a class="reference internal" href="#enriching-exceptions-with-notes">8.10. Enriching Exceptions with Notes</a></li>
  782. </ul>
  783. </li>
  784. </ul>
  785. </div>
  786. <div>
  787. <h4>Previous topic</h4>
  788. <p class="topless"><a href="inputoutput.html"
  789. title="previous chapter"><span class="section-number">7. </span>Input and Output</a></p>
  790. </div>
  791. <div>
  792. <h4>Next topic</h4>
  793. <p class="topless"><a href="classes.html"
  794. title="next chapter"><span class="section-number">9. </span>Classes</a></p>
  795. </div>
  796. <div role="note" aria-label="source link">
  797. <h3>This Page</h3>
  798. <ul class="this-page-menu">
  799. <li><a href="../bugs.html">Report a Bug</a></li>
  800. <li>
  801. <a href="https://github.com/python/cpython/blob/main/Doc/tutorial/errors.rst"
  802. rel="nofollow">Show Source
  803. </a>
  804. </li>
  805. </ul>
  806. </div>
  807. </div>
  808. </div>
  809. <div class="clearer"></div>
  810. </div>
  811. <div class="related" role="navigation" aria-label="related navigation">
  812. <h3>Navigation</h3>
  813. <ul>
  814. <li class="right" style="margin-right: 10px">
  815. <a href="../genindex.html" title="General Index"
  816. >index</a></li>
  817. <li class="right" >
  818. <a href="../py-modindex.html" title="Python Module Index"
  819. >modules</a> |</li>
  820. <li class="right" >
  821. <a href="classes.html" title="9. Classes"
  822. >next</a> |</li>
  823. <li class="right" >
  824. <a href="inputoutput.html" title="7. Input and Output"
  825. >previous</a> |</li>
  826. <li><img src="../_static/py.svg" alt="python logo" style="vertical-align: middle; margin-top: -1px"/></li>
  827. <li><a href="https://www.python.org/">Python</a> &#187;</li>
  828. <li class="switchers">
  829. <div class="language_switcher_placeholder"></div>
  830. <div class="version_switcher_placeholder"></div>
  831. </li>
  832. <li>
  833. </li>
  834. <li id="cpython-language-and-version">
  835. <a href="../index.html">3.12.0 Documentation</a> &#187;
  836. </li>
  837. <li class="nav-item nav-item-1"><a href="index.html" >The Python Tutorial</a> &#187;</li>
  838. <li class="nav-item nav-item-this"><a href=""><span class="section-number">8. </span>Errors and Exceptions</a></li>
  839. <li class="right">
  840. <div class="inline-search" role="search">
  841. <form class="inline-search" action="../search.html" method="get">
  842. <input placeholder="Quick search" aria-label="Quick search" type="search" name="q" />
  843. <input type="submit" value="Go" />
  844. </form>
  845. </div>
  846. |
  847. </li>
  848. <li class="right">
  849. <label class="theme-selector-label">
  850. Theme
  851. <select class="theme-selector" oninput="activateTheme(this.value)">
  852. <option value="auto" selected>Auto</option>
  853. <option value="light">Light</option>
  854. <option value="dark">Dark</option>
  855. </select>
  856. </label> |</li>
  857. </ul>
  858. </div>
  859. <div class="footer">
  860. &copy; <a href="../copyright.html">Copyright</a> 2001-2023, Python Software Foundation.
  861. <br />
  862. This page is licensed under the Python Software Foundation License Version 2.
  863. <br />
  864. Examples, recipes, and other code in the documentation are additionally licensed under the Zero Clause BSD License.
  865. <br />
  866. See <a href="/license.html">History and License</a> for more information.<br />
  867. <br />
  868. The Python Software Foundation is a non-profit corporation.
  869. <a href="https://www.python.org/psf/donations/">Please donate.</a>
  870. <br />
  871. <br />
  872. Last updated on Oct 02, 2023.
  873. <a href="/bugs.html">Found a bug</a>?
  874. <br />
  875. Created using <a href="https://www.sphinx-doc.org/">Sphinx</a> 4.5.0.
  876. </div>
  877. </body>
  878. </html>