123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924 |
- <!DOCTYPE html>
- <html>
- <head>
- <meta charset="utf-8" />
- <meta name="viewport" content="width=device-width, initial-scale=1.0" /><meta name="generator" content="Docutils 0.17.1: http://docutils.sourceforge.net/" />
- <meta property="og:title" content="8. Errors and Exceptions" />
- <meta property="og:type" content="website" />
- <meta property="og:url" content="https://docs.python.org/3/tutorial/errors.html" />
- <meta property="og:site_name" content="Python documentation" />
- <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..." />
- <meta property="og:image" content="https://docs.python.org/3/_static/og-image.png" />
- <meta property="og:image:alt" content="Python documentation" />
- <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..." />
- <meta property="og:image:width" content="200" />
- <meta property="og:image:height" content="200" />
- <meta name="theme-color" content="#3776ab" />
- <title>8. Errors and Exceptions — Python 3.12.0 documentation</title><meta name="viewport" content="width=device-width, initial-scale=1.0">
-
- <link rel="stylesheet" type="text/css" href="../_static/pygments.css" />
- <link rel="stylesheet" type="text/css" href="../_static/pydoctheme.css?digest=b37c26da2f7529d09fe70b41c4b2133fe4931a90" />
- <link id="pygments_dark_css" media="(prefers-color-scheme: dark)" rel="stylesheet" type="text/css" href="../_static/pygments_dark.css" />
-
- <script data-url_root="../" id="documentation_options" src="../_static/documentation_options.js"></script>
- <script src="../_static/jquery.js"></script>
- <script src="../_static/underscore.js"></script>
- <script src="../_static/doctools.js"></script>
-
- <script src="../_static/sidebar.js"></script>
-
- <link rel="search" type="application/opensearchdescription+xml"
- title="Search within Python 3.12.0 documentation"
- href="../_static/opensearch.xml"/>
- <link rel="author" title="About these documents" href="../about.html" />
- <link rel="index" title="Index" href="../genindex.html" />
- <link rel="search" title="Search" href="../search.html" />
- <link rel="copyright" title="Copyright" href="../copyright.html" />
- <link rel="next" title="9. Classes" href="classes.html" />
- <link rel="prev" title="7. Input and Output" href="inputoutput.html" />
- <link rel="canonical" href="https://docs.python.org/3/tutorial/errors.html" />
-
-
-
-
- <style>
- @media only screen {
- table.full-width-table {
- width: 100%;
- }
- }
- </style>
- <link rel="stylesheet" href="../_static/pydoctheme_dark.css" media="(prefers-color-scheme: dark)" id="pydoctheme_dark_css">
- <link rel="shortcut icon" type="image/png" href="../_static/py.svg" />
- <script type="text/javascript" src="../_static/copybutton.js"></script>
- <script type="text/javascript" src="../_static/menu.js"></script>
- <script type="text/javascript" src="../_static/themetoggle.js"></script>
- </head>
- <body>
- <div class="mobile-nav">
- <input type="checkbox" id="menuToggler" class="toggler__input" aria-controls="navigation"
- aria-pressed="false" aria-expanded="false" role="button" aria-label="Menu" />
- <nav class="nav-content" role="navigation">
- <label for="menuToggler" class="toggler__label">
- <span></span>
- </label>
- <span class="nav-items-wrapper">
- <a href="https://www.python.org/" class="nav-logo">
- <img src="../_static/py.svg" alt="Logo"/>
- </a>
- <span class="version_switcher_placeholder"></span>
- <form role="search" class="search" action="../search.html" method="get">
- <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" class="search-icon">
- <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>
- </svg>
- <input placeholder="Quick search" aria-label="Quick search" type="search" name="q" />
- <input type="submit" value="Go"/>
- </form>
- </span>
- </nav>
- <div class="menu-wrapper">
- <nav class="menu" role="navigation" aria-label="main navigation">
- <div class="language_switcher_placeholder"></div>
-
- <label class="theme-selector-label">
- Theme
- <select class="theme-selector" oninput="activateTheme(this.value)">
- <option value="auto" selected>Auto</option>
- <option value="light">Light</option>
- <option value="dark">Dark</option>
- </select>
- </label>
- <div>
- <h3><a href="../contents.html">Table of Contents</a></h3>
- <ul>
- <li><a class="reference internal" href="#">8. Errors and Exceptions</a><ul>
- <li><a class="reference internal" href="#syntax-errors">8.1. Syntax Errors</a></li>
- <li><a class="reference internal" href="#exceptions">8.2. Exceptions</a></li>
- <li><a class="reference internal" href="#handling-exceptions">8.3. Handling Exceptions</a></li>
- <li><a class="reference internal" href="#raising-exceptions">8.4. Raising Exceptions</a></li>
- <li><a class="reference internal" href="#exception-chaining">8.5. Exception Chaining</a></li>
- <li><a class="reference internal" href="#user-defined-exceptions">8.6. User-defined Exceptions</a></li>
- <li><a class="reference internal" href="#defining-clean-up-actions">8.7. Defining Clean-up Actions</a></li>
- <li><a class="reference internal" href="#predefined-clean-up-actions">8.8. Predefined Clean-up Actions</a></li>
- <li><a class="reference internal" href="#raising-and-handling-multiple-unrelated-exceptions">8.9. Raising and Handling Multiple Unrelated Exceptions</a></li>
- <li><a class="reference internal" href="#enriching-exceptions-with-notes">8.10. Enriching Exceptions with Notes</a></li>
- </ul>
- </li>
- </ul>
- </div>
- <div>
- <h4>Previous topic</h4>
- <p class="topless"><a href="inputoutput.html"
- title="previous chapter"><span class="section-number">7. </span>Input and Output</a></p>
- </div>
- <div>
- <h4>Next topic</h4>
- <p class="topless"><a href="classes.html"
- title="next chapter"><span class="section-number">9. </span>Classes</a></p>
- </div>
- <div role="note" aria-label="source link">
- <h3>This Page</h3>
- <ul class="this-page-menu">
- <li><a href="../bugs.html">Report a Bug</a></li>
- <li>
- <a href="https://github.com/python/cpython/blob/main/Doc/tutorial/errors.rst"
- rel="nofollow">Show Source
- </a>
- </li>
- </ul>
- </div>
- </nav>
- </div>
- </div>
-
- <div class="related" role="navigation" aria-label="related navigation">
- <h3>Navigation</h3>
- <ul>
- <li class="right" style="margin-right: 10px">
- <a href="../genindex.html" title="General Index"
- accesskey="I">index</a></li>
- <li class="right" >
- <a href="../py-modindex.html" title="Python Module Index"
- >modules</a> |</li>
- <li class="right" >
- <a href="classes.html" title="9. Classes"
- accesskey="N">next</a> |</li>
- <li class="right" >
- <a href="inputoutput.html" title="7. Input and Output"
- accesskey="P">previous</a> |</li>
- <li><img src="../_static/py.svg" alt="python logo" style="vertical-align: middle; margin-top: -1px"/></li>
- <li><a href="https://www.python.org/">Python</a> »</li>
- <li class="switchers">
- <div class="language_switcher_placeholder"></div>
- <div class="version_switcher_placeholder"></div>
- </li>
- <li>
-
- </li>
- <li id="cpython-language-and-version">
- <a href="../index.html">3.12.0 Documentation</a> »
- </li>
- <li class="nav-item nav-item-1"><a href="index.html" accesskey="U">The Python Tutorial</a> »</li>
- <li class="nav-item nav-item-this"><a href=""><span class="section-number">8. </span>Errors and Exceptions</a></li>
- <li class="right">
-
- <div class="inline-search" role="search">
- <form class="inline-search" action="../search.html" method="get">
- <input placeholder="Quick search" aria-label="Quick search" type="search" name="q" />
- <input type="submit" value="Go" />
- </form>
- </div>
- |
- </li>
- <li class="right">
- <label class="theme-selector-label">
- Theme
- <select class="theme-selector" oninput="activateTheme(this.value)">
- <option value="auto" selected>Auto</option>
- <option value="light">Light</option>
- <option value="dark">Dark</option>
- </select>
- </label> |</li>
-
- </ul>
- </div>
- <div class="document">
- <div class="documentwrapper">
- <div class="bodywrapper">
- <div class="body" role="main">
-
- <section id="errors-and-exceptions">
- <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>
- <p>Until now error messages haven’t been more than mentioned, but if you have tried
- out the examples you have probably seen some. There are (at least) two
- distinguishable kinds of errors: <em>syntax errors</em> and <em>exceptions</em>.</p>
- <section id="syntax-errors">
- <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>
- <p>Syntax errors, also known as parsing errors, are perhaps the most common kind of
- complaint you get while you are still learning Python:</p>
- <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="k">while</span> <span class="kc">True</span> <span class="nb">print</span><span class="p">(</span><span class="s1">'Hello world'</span><span class="p">)</span>
- File <span class="nb">"<stdin>"</span>, line <span class="m">1</span>
- <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">'Hello world'</span><span class="p">)</span>
- <span class="w"> </span><span class="pm">^</span>
- <span class="gr">SyntaxError</span>: <span class="n">invalid syntax</span>
- </pre></div>
- </div>
- <p>The parser repeats the offending line and displays a little ‘arrow’ pointing at
- the earliest point in the line where the error was detected. The error is
- caused by (or at least detected at) the token <em>preceding</em> the arrow: in the
- example, the error is detected at the function <a 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
- (<code class="docutils literal notranslate"><span class="pre">':'</span></code>) is missing before it. File name and line number are printed so you
- know where to look in case the input came from a script.</p>
- </section>
- <section id="exceptions">
- <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>
- <p>Even if a statement or expression is syntactically correct, it may cause an
- error when an attempt is made to execute it. Errors detected during execution
- are called <em>exceptions</em> and are not unconditionally fatal: you will soon learn
- how to handle them in Python programs. Most exceptions are not handled by
- programs, however, and result in error messages as shown here:</p>
- <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </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>
- <span class="gt">Traceback (most recent call last):</span>
- File <span class="nb">"<stdin>"</span>, line <span class="m">1</span>, in <span class="n"><module></span>
- <span class="gr">ZeroDivisionError</span>: <span class="n">division by zero</span>
- <span class="gp">>>> </span><span class="mi">4</span> <span class="o">+</span> <span class="n">spam</span><span class="o">*</span><span class="mi">3</span>
- <span class="gt">Traceback (most recent call last):</span>
- File <span class="nb">"<stdin>"</span>, line <span class="m">1</span>, in <span class="n"><module></span>
- <span class="gr">NameError</span>: <span class="n">name 'spam' is not defined</span>
- <span class="gp">>>> </span><span class="s1">'2'</span> <span class="o">+</span> <span class="mi">2</span>
- <span class="gt">Traceback (most recent call last):</span>
- File <span class="nb">"<stdin>"</span>, line <span class="m">1</span>, in <span class="n"><module></span>
- <span class="gr">TypeError</span>: <span class="n">can only concatenate str (not "int") to str</span>
- </pre></div>
- </div>
- <p>The last line of the error message indicates what happened. Exceptions come in
- different types, and the type is printed as part of the message: the types in
- the example are <a 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>.
- The string printed as the exception type is the name of the built-in exception
- that occurred. This is true for all built-in exceptions, but need not be true
- for user-defined exceptions (although it is a useful convention). Standard
- exception names are built-in identifiers (not reserved keywords).</p>
- <p>The rest of the line provides detail based on the type of exception and what
- caused it.</p>
- <p>The preceding part of the error message shows the context where the exception
- occurred, in the form of a stack traceback. In general it contains a stack
- traceback listing source lines; however, it will not display lines read from
- standard input.</p>
- <p><a 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>
- </section>
- <section id="handling-exceptions">
- <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>
- <p>It is possible to write programs that handle selected exceptions. Look at the
- following example, which asks the user for input until a valid integer has been
- entered, but allows the user to interrupt the program (using <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
- whatever the operating system supports); note that a user-generated interruption
- 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>
- <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="k">while</span> <span class="kc">True</span><span class="p">:</span>
- <span class="gp">... </span> <span class="k">try</span><span class="p">:</span>
- <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">"Please enter a number: "</span><span class="p">))</span>
- <span class="gp">... </span> <span class="k">break</span>
- <span class="gp">... </span> <span class="k">except</span> <span class="ne">ValueError</span><span class="p">:</span>
- <span class="gp">... </span> <span class="nb">print</span><span class="p">(</span><span class="s2">"Oops! That was no valid number. Try again..."</span><span class="p">)</span>
- <span class="gp">...</span>
- </pre></div>
- </div>
- <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>
- <ul class="simple">
- <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
- <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>
- <li><p>If no exception occurs, the <em>except clause</em> is skipped and 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> statement is finished.</p></li>
- <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
- clause is skipped. Then, if its type matches the exception named after the
- <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
- continues after the try/except block.</p></li>
- <li><p>If an exception occurs which does not match the exception named in the <em>except
- 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
- found, it is an <em>unhandled exception</em> and execution stops with a message as
- shown above.</p></li>
- </ul>
- <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
- handlers for different exceptions. At most one handler will be executed.
- Handlers only handle exceptions that occur in the corresponding <em>try clause</em>,
- 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>
- may name multiple exceptions as a parenthesized tuple, for example:</p>
- <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>
- <span class="o">...</span> <span class="k">pass</span>
- </pre></div>
- </div>
- <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
- the same class or a base class thereof (but not the other way around — an
- <em>except clause</em> listing a derived class is not compatible with a base class).
- For example, the following code will print B, C, D in that order:</p>
- <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>
- <span class="k">pass</span>
- <span class="k">class</span> <span class="nc">C</span><span class="p">(</span><span class="n">B</span><span class="p">):</span>
- <span class="k">pass</span>
- <span class="k">class</span> <span class="nc">D</span><span class="p">(</span><span class="n">C</span><span class="p">):</span>
- <span class="k">pass</span>
- <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>
- <span class="k">try</span><span class="p">:</span>
- <span class="k">raise</span> <span class="bp">cls</span><span class="p">()</span>
- <span class="k">except</span> <span class="n">D</span><span class="p">:</span>
- <span class="nb">print</span><span class="p">(</span><span class="s2">"D"</span><span class="p">)</span>
- <span class="k">except</span> <span class="n">C</span><span class="p">:</span>
- <span class="nb">print</span><span class="p">(</span><span class="s2">"C"</span><span class="p">)</span>
- <span class="k">except</span> <span class="n">B</span><span class="p">:</span>
- <span class="nb">print</span><span class="p">(</span><span class="s2">"B"</span><span class="p">)</span>
- </pre></div>
- </div>
- <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
- would have printed B, B, B — the first matching <em>except clause</em> is triggered.</p>
- <p>When an exception occurs, it may have associated values, also known as the
- exception’s <em>arguments</em>. The presence and types of the arguments depend on the
- exception type.</p>
- <p>The <em>except clause</em> may specify a variable after the exception name. The
- variable is bound to the exception instance which typically has an <code class="docutils literal notranslate"><span class="pre">args</span></code>
- attribute that stores the arguments. For convenience, builtin exception
- 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
- accessing <code class="docutils literal notranslate"><span class="pre">.args</span></code>.</p>
- <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="k">try</span><span class="p">:</span>
- <span class="gp">... </span> <span class="k">raise</span> <span class="ne">Exception</span><span class="p">(</span><span class="s1">'spam'</span><span class="p">,</span> <span class="s1">'eggs'</span><span class="p">)</span>
- <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>
- <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>
- <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>
- <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>
- <span class="gp">... </span> <span class="c1"># but may be overridden in exception subclasses</span>
- <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>
- <span class="gp">... </span> <span class="nb">print</span><span class="p">(</span><span class="s1">'x ='</span><span class="p">,</span> <span class="n">x</span><span class="p">)</span>
- <span class="gp">... </span> <span class="nb">print</span><span class="p">(</span><span class="s1">'y ='</span><span class="p">,</span> <span class="n">y</span><span class="p">)</span>
- <span class="gp">...</span>
- <span class="go"><class 'Exception'></span>
- <span class="go">('spam', 'eggs')</span>
- <span class="go">('spam', 'eggs')</span>
- <span class="go">x = spam</span>
- <span class="go">y = eggs</span>
- </pre></div>
- </div>
- <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’)
- of the message for unhandled exceptions.</p>
- <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
- 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.
- 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
- handled, because they are used to indicate that the program should terminate.
- 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
- <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
- the program.</p>
- <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.
- However, it is good practice to be as specific as possible with the types
- of exceptions that we intend to handle, and to allow any unexpected
- exceptions to propagate on.</p>
- <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
- the exception and then re-raise it (allowing a caller to handle the
- exception as well):</p>
- <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">sys</span>
- <span class="k">try</span><span class="p">:</span>
- <span class="n">f</span> <span class="o">=</span> <span class="nb">open</span><span class="p">(</span><span class="s1">'myfile.txt'</span><span class="p">)</span>
- <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>
- <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>
- <span class="k">except</span> <span class="ne">OSError</span> <span class="k">as</span> <span class="n">err</span><span class="p">:</span>
- <span class="nb">print</span><span class="p">(</span><span class="s2">"OS error:"</span><span class="p">,</span> <span class="n">err</span><span class="p">)</span>
- <span class="k">except</span> <span class="ne">ValueError</span><span class="p">:</span>
- <span class="nb">print</span><span class="p">(</span><span class="s2">"Could not convert data to an integer."</span><span class="p">)</span>
- <span class="k">except</span> <span class="ne">Exception</span> <span class="k">as</span> <span class="n">err</span><span class="p">:</span>
- <span class="nb">print</span><span class="p">(</span><span class="sa">f</span><span class="s2">"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">"</span><span class="p">)</span>
- <span class="k">raise</span>
- </pre></div>
- </div>
- <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
- clause</em>, which, when present, must follow all <em>except clauses</em>. It is useful
- for code that must be executed if the <em>try clause</em> does not raise an exception.
- For example:</p>
- <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>
- <span class="k">try</span><span class="p">:</span>
- <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">'r'</span><span class="p">)</span>
- <span class="k">except</span> <span class="ne">OSError</span><span class="p">:</span>
- <span class="nb">print</span><span class="p">(</span><span class="s1">'cannot open'</span><span class="p">,</span> <span class="n">arg</span><span class="p">)</span>
- <span class="k">else</span><span class="p">:</span>
- <span class="nb">print</span><span class="p">(</span><span class="n">arg</span><span class="p">,</span> <span class="s1">'has'</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">'lines'</span><span class="p">)</span>
- <span class="n">f</span><span class="o">.</span><span class="n">close</span><span class="p">()</span>
- </pre></div>
- </div>
- <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
- 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
- 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> …
- <code class="xref std std-keyword docutils literal notranslate"><span class="pre">except</span></code> statement.</p>
- <p>Exception handlers do not handle only exceptions that occur immediately in the
- <em>try clause</em>, but also those that occur inside functions that are called (even
- indirectly) in the <em>try clause</em>. For example:</p>
- <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="k">def</span> <span class="nf">this_fails</span><span class="p">():</span>
- <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>
- <span class="gp">...</span>
- <span class="gp">>>> </span><span class="k">try</span><span class="p">:</span>
- <span class="gp">... </span> <span class="n">this_fails</span><span class="p">()</span>
- <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>
- <span class="gp">... </span> <span class="nb">print</span><span class="p">(</span><span class="s1">'Handling run-time error:'</span><span class="p">,</span> <span class="n">err</span><span class="p">)</span>
- <span class="gp">...</span>
- <span class="go">Handling run-time error: division by zero</span>
- </pre></div>
- </div>
- </section>
- <section id="raising-exceptions">
- <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>
- <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
- exception to occur. For example:</p>
- <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="k">raise</span> <span class="ne">NameError</span><span class="p">(</span><span class="s1">'HiThere'</span><span class="p">)</span>
- <span class="gt">Traceback (most recent call last):</span>
- File <span class="nb">"<stdin>"</span>, line <span class="m">1</span>, in <span class="n"><module></span>
- <span class="gr">NameError</span>: <span class="n">HiThere</span>
- </pre></div>
- </div>
- <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.
- This must be either an exception instance or an exception class (a class that
- 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
- subclasses). If an exception class is passed, it will be implicitly
- instantiated by calling its constructor with no arguments:</p>
- <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 'raise ValueError()'</span>
- </pre></div>
- </div>
- <p>If you need to determine whether an exception was raised but don’t intend to
- 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
- re-raise the exception:</p>
- <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="k">try</span><span class="p">:</span>
- <span class="gp">... </span> <span class="k">raise</span> <span class="ne">NameError</span><span class="p">(</span><span class="s1">'HiThere'</span><span class="p">)</span>
- <span class="gp">... </span><span class="k">except</span> <span class="ne">NameError</span><span class="p">:</span>
- <span class="gp">... </span> <span class="nb">print</span><span class="p">(</span><span class="s1">'An exception flew by!'</span><span class="p">)</span>
- <span class="gp">... </span> <span class="k">raise</span>
- <span class="gp">...</span>
- <span class="go">An exception flew by!</span>
- <span class="gt">Traceback (most recent call last):</span>
- File <span class="nb">"<stdin>"</span>, line <span class="m">2</span>, in <span class="n"><module></span>
- <span class="gr">NameError</span>: <span class="n">HiThere</span>
- </pre></div>
- </div>
- </section>
- <section id="exception-chaining">
- <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>
- <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
- have the exception being handled attached to it and included in the error
- message:</p>
- <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="k">try</span><span class="p">:</span>
- <span class="gp">... </span> <span class="nb">open</span><span class="p">(</span><span class="s2">"database.sqlite"</span><span class="p">)</span>
- <span class="gp">... </span><span class="k">except</span> <span class="ne">OSError</span><span class="p">:</span>
- <span class="gp">... </span> <span class="k">raise</span> <span class="ne">RuntimeError</span><span class="p">(</span><span class="s2">"unable to handle error"</span><span class="p">)</span>
- <span class="gp">...</span>
- <span class="gt">Traceback (most recent call last):</span>
- File <span class="nb">"<stdin>"</span>, line <span class="m">2</span>, in <span class="n"><module></span>
- <span class="gr">FileNotFoundError</span>: <span class="n">[Errno 2] No such file or directory: 'database.sqlite'</span>
- <span class="gt">During handling of the above exception, another exception occurred:</span>
- <span class="gt">Traceback (most recent call last):</span>
- File <span class="nb">"<stdin>"</span>, line <span class="m">4</span>, in <span class="n"><module></span>
- <span class="gr">RuntimeError</span>: <span class="n">unable to handle error</span>
- </pre></div>
- </div>
- <p>To indicate that an exception is a direct consequence of another, 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 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>
- <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="c1"># exc must be exception instance or None.</span>
- <span class="k">raise</span> <span class="ne">RuntimeError</span> <span class="kn">from</span> <span class="nn">exc</span>
- </pre></div>
- </div>
- <p>This can be useful when you are transforming exceptions. For example:</p>
- <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="k">def</span> <span class="nf">func</span><span class="p">():</span>
- <span class="gp">... </span> <span class="k">raise</span> <span class="ne">ConnectionError</span>
- <span class="gp">...</span>
- <span class="gp">>>> </span><span class="k">try</span><span class="p">:</span>
- <span class="gp">... </span> <span class="n">func</span><span class="p">()</span>
- <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>
- <span class="gp">... </span> <span class="k">raise</span> <span class="ne">RuntimeError</span><span class="p">(</span><span class="s1">'Failed to open database'</span><span class="p">)</span> <span class="kn">from</span> <span class="nn">exc</span>
- <span class="gp">...</span>
- <span class="gt">Traceback (most recent call last):</span>
- File <span class="nb">"<stdin>"</span>, line <span class="m">2</span>, in <span class="n"><module></span>
- File <span class="nb">"<stdin>"</span>, line <span class="m">2</span>, in <span class="n">func</span>
- <span class="gr">ConnectionError</span>
- <span class="gt">The above exception was the direct cause of the following exception:</span>
- <span class="gt">Traceback (most recent call last):</span>
- File <span class="nb">"<stdin>"</span>, line <span class="m">4</span>, in <span class="n"><module></span>
- <span class="gr">RuntimeError</span>: <span class="n">Failed to open database</span>
- </pre></div>
- </div>
- <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>
- idiom:</p>
- <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="k">try</span><span class="p">:</span>
- <span class="gp">... </span> <span class="nb">open</span><span class="p">(</span><span class="s1">'database.sqlite'</span><span class="p">)</span>
- <span class="gp">... </span><span class="k">except</span> <span class="ne">OSError</span><span class="p">:</span>
- <span class="gp">... </span> <span class="k">raise</span> <span class="ne">RuntimeError</span> <span class="kn">from</span> <span class="kc">None</span>
- <span class="gp">...</span>
- <span class="gt">Traceback (most recent call last):</span>
- File <span class="nb">"<stdin>"</span>, line <span class="m">4</span>, in <span class="n"><module></span>
- <span class="gr">RuntimeError</span>
- </pre></div>
- </div>
- <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>
- </section>
- <section id="user-defined-exceptions">
- <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>
- <p>Programs may name their own exceptions by creating a new exception class (see
- <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
- 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>
- <p>Exception classes can be defined which do anything any other class can do, but
- are usually kept simple, often only offering a number of attributes that allow
- information about the error to be extracted by handlers for the exception.</p>
- <p>Most exceptions are defined with names that end in “Error”, similar to the
- naming of the standard exceptions.</p>
- <p>Many standard modules define their own exceptions to report errors that may
- occur in functions they define.</p>
- </section>
- <section id="defining-clean-up-actions">
- <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>
- <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
- define clean-up actions that must be executed under all circumstances. For
- example:</p>
- <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="k">try</span><span class="p">:</span>
- <span class="gp">... </span> <span class="k">raise</span> <span class="ne">KeyboardInterrupt</span>
- <span class="gp">... </span><span class="k">finally</span><span class="p">:</span>
- <span class="gp">... </span> <span class="nb">print</span><span class="p">(</span><span class="s1">'Goodbye, world!'</span><span class="p">)</span>
- <span class="gp">...</span>
- <span class="go">Goodbye, world!</span>
- <span class="gt">Traceback (most recent call last):</span>
- File <span class="nb">"<stdin>"</span>, line <span class="m">2</span>, in <span class="n"><module></span>
- <span class="nc">KeyboardInterrupt</span>
- </pre></div>
- </div>
- <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>
- 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>
- statement completes. The <code class="xref std std-keyword docutils literal notranslate"><span class="pre">finally</span></code> clause runs whether or
- not the <code class="xref std std-keyword docutils literal notranslate"><span class="pre">try</span></code> statement produces an exception. The following
- points discuss more complex cases when an exception occurs:</p>
- <ul class="simple">
- <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>
- 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>
- clause. If the exception is not handled by an <code class="xref std std-keyword docutils literal notranslate"><span class="pre">except</span></code>
- clause, the exception is re-raised after the <code class="xref std std-keyword docutils literal notranslate"><span class="pre">finally</span></code>
- clause has been executed.</p></li>
- <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>
- or <code class="xref std std-keyword docutils literal notranslate"><span class="pre">else</span></code> clause. Again, the exception is re-raised after
- the <code class="xref std std-keyword docutils literal notranslate"><span class="pre">finally</span></code> clause has been executed.</p></li>
- <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>,
- <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
- re-raised.</p></li>
- <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>,
- <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
- <code class="xref std std-keyword docutils literal notranslate"><span class="pre">finally</span></code> clause will execute just prior to the
- <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>
- statement’s execution.</p></li>
- <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>
- statement, the returned value will be the one from the
- <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
- 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>
- statement.</p></li>
- </ul>
- <p>For example:</p>
- <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="k">def</span> <span class="nf">bool_return</span><span class="p">():</span>
- <span class="gp">... </span> <span class="k">try</span><span class="p">:</span>
- <span class="gp">... </span> <span class="k">return</span> <span class="kc">True</span>
- <span class="gp">... </span> <span class="k">finally</span><span class="p">:</span>
- <span class="gp">... </span> <span class="k">return</span> <span class="kc">False</span>
- <span class="gp">...</span>
- <span class="gp">>>> </span><span class="n">bool_return</span><span class="p">()</span>
- <span class="go">False</span>
- </pre></div>
- </div>
- <p>A more complicated example:</p>
- <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </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>
- <span class="gp">... </span> <span class="k">try</span><span class="p">:</span>
- <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>
- <span class="gp">... </span> <span class="k">except</span> <span class="ne">ZeroDivisionError</span><span class="p">:</span>
- <span class="gp">... </span> <span class="nb">print</span><span class="p">(</span><span class="s2">"division by zero!"</span><span class="p">)</span>
- <span class="gp">... </span> <span class="k">else</span><span class="p">:</span>
- <span class="gp">... </span> <span class="nb">print</span><span class="p">(</span><span class="s2">"result is"</span><span class="p">,</span> <span class="n">result</span><span class="p">)</span>
- <span class="gp">... </span> <span class="k">finally</span><span class="p">:</span>
- <span class="gp">... </span> <span class="nb">print</span><span class="p">(</span><span class="s2">"executing finally clause"</span><span class="p">)</span>
- <span class="gp">...</span>
- <span class="gp">>>> </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>
- <span class="go">result is 2.0</span>
- <span class="go">executing finally clause</span>
- <span class="gp">>>> </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>
- <span class="go">division by zero!</span>
- <span class="go">executing finally clause</span>
- <span class="gp">>>> </span><span class="n">divide</span><span class="p">(</span><span class="s2">"2"</span><span class="p">,</span> <span class="s2">"1"</span><span class="p">)</span>
- <span class="go">executing finally clause</span>
- <span class="gt">Traceback (most recent call last):</span>
- File <span class="nb">"<stdin>"</span>, line <span class="m">1</span>, in <span class="n"><module></span>
- File <span class="nb">"<stdin>"</span>, line <span class="m">3</span>, in <span class="n">divide</span>
- <span class="gr">TypeError</span>: <span class="n">unsupported operand type(s) for /: 'str' and 'str'</span>
- </pre></div>
- </div>
- <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
- <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
- <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>
- clause has been executed.</p>
- <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
- releasing external resources (such as files or network connections), regardless
- of whether the use of the resource was successful.</p>
- </section>
- <section id="predefined-clean-up-actions">
- <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>
- <p>Some objects define standard clean-up actions to be undertaken when the object
- is no longer needed, regardless of whether or not the operation using the object
- succeeded or failed. Look at the following example, which tries to open a file
- and print its contents to the screen.</p>
- <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">"myfile.txt"</span><span class="p">):</span>
- <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">""</span><span class="p">)</span>
- </pre></div>
- </div>
- <p>The problem with this code is that it leaves the file open for an indeterminate
- amount of time after this part of the code has finished executing.
- This is not an issue in simple scripts, but can be a problem for larger
- applications. The <a 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
- used in a way that ensures they are always cleaned up promptly and correctly.</p>
- <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">"myfile.txt"</span><span class="p">)</span> <span class="k">as</span> <span class="n">f</span><span class="p">:</span>
- <span class="k">for</span> <span class="n">line</span> <span class="ow">in</span> <span class="n">f</span><span class="p">:</span>
- <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">""</span><span class="p">)</span>
- </pre></div>
- </div>
- <p>After the statement is executed, the file <em>f</em> is always closed, even if a
- problem was encountered while processing the lines. Objects which, like files,
- provide predefined clean-up actions will indicate this in their documentation.</p>
- </section>
- <section id="raising-and-handling-multiple-unrelated-exceptions">
- <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>
- <p>There are situations where it is necessary to report several exceptions that
- have occurred. This is often the case in concurrency frameworks, when several
- tasks may have failed in parallel, but there are also other use cases where
- it is desirable to continue execution and collect multiple errors rather than
- raise the first exception.</p>
- <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
- that they can be raised together. It is an exception itself, so it can be
- caught like any other exception.</p>
- <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="k">def</span> <span class="nf">f</span><span class="p">():</span>
- <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">'error 1'</span><span class="p">),</span> <span class="ne">SystemError</span><span class="p">(</span><span class="s1">'error 2'</span><span class="p">)]</span>
- <span class="gp">... </span> <span class="k">raise</span> <span class="n">ExceptionGroup</span><span class="p">(</span><span class="s1">'there were problems'</span><span class="p">,</span> <span class="n">excs</span><span class="p">)</span>
- <span class="gp">...</span>
- <span class="gp">>>> </span><span class="n">f</span><span class="p">()</span>
- <span class="go"> + Exception Group Traceback (most recent call last):</span>
- <span class="go"> | File "<stdin>", line 1, in <module></span>
- <span class="go"> | File "<stdin>", line 3, in f</span>
- <span class="go"> | ExceptionGroup: there were problems</span>
- <span class="go"> +-+---------------- 1 ----------------</span>
- <span class="go"> | OSError: error 1</span>
- <span class="go"> +---------------- 2 ----------------</span>
- <span class="go"> | SystemError: error 2</span>
- <span class="go"> +------------------------------------</span>
- <span class="gp">>>> </span><span class="k">try</span><span class="p">:</span>
- <span class="gp">... </span> <span class="n">f</span><span class="p">()</span>
- <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>
- <span class="gp">... </span> <span class="nb">print</span><span class="p">(</span><span class="sa">f</span><span class="s1">'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'</span><span class="p">)</span>
- <span class="gp">...</span>
- <span class="go">caught <class 'ExceptionGroup'>: e</span>
- <span class="gp">>>></span>
- </pre></div>
- </div>
- <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
- handle only the exceptions in the group that match a certain
- type. In the following example, which shows a nested exception
- group, each <code class="docutils literal notranslate"><span class="pre">except*</span></code> clause extracts from the group exceptions
- of a certain type while letting all other exceptions propagate to
- other clauses and eventually to be reraised.</p>
- <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="k">def</span> <span class="nf">f</span><span class="p">():</span>
- <span class="gp">... </span> <span class="k">raise</span> <span class="n">ExceptionGroup</span><span class="p">(</span>
- <span class="gp">... </span> <span class="s2">"group1"</span><span class="p">,</span>
- <span class="gp">... </span> <span class="p">[</span>
- <span class="gp">... </span> <span class="ne">OSError</span><span class="p">(</span><span class="mi">1</span><span class="p">),</span>
- <span class="gp">... </span> <span class="ne">SystemError</span><span class="p">(</span><span class="mi">2</span><span class="p">),</span>
- <span class="gp">... </span> <span class="n">ExceptionGroup</span><span class="p">(</span>
- <span class="gp">... </span> <span class="s2">"group2"</span><span class="p">,</span>
- <span class="gp">... </span> <span class="p">[</span>
- <span class="gp">... </span> <span class="ne">OSError</span><span class="p">(</span><span class="mi">3</span><span class="p">),</span>
- <span class="gp">... </span> <span class="ne">RecursionError</span><span class="p">(</span><span class="mi">4</span><span class="p">)</span>
- <span class="gp">... </span> <span class="p">]</span>
- <span class="gp">... </span> <span class="p">)</span>
- <span class="gp">... </span> <span class="p">]</span>
- <span class="gp">... </span> <span class="p">)</span>
- <span class="gp">...</span>
- <span class="gp">>>> </span><span class="k">try</span><span class="p">:</span>
- <span class="gp">... </span> <span class="n">f</span><span class="p">()</span>
- <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>
- <span class="gp">... </span> <span class="nb">print</span><span class="p">(</span><span class="s2">"There were OSErrors"</span><span class="p">)</span>
- <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>
- <span class="gp">... </span> <span class="nb">print</span><span class="p">(</span><span class="s2">"There were SystemErrors"</span><span class="p">)</span>
- <span class="gp">...</span>
- <span class="go">There were OSErrors</span>
- <span class="go">There were SystemErrors</span>
- <span class="go"> + Exception Group Traceback (most recent call last):</span>
- <span class="go"> | File "<stdin>", line 2, in <module></span>
- <span class="go"> | File "<stdin>", line 2, in f</span>
- <span class="go"> | ExceptionGroup: group1</span>
- <span class="go"> +-+---------------- 1 ----------------</span>
- <span class="go"> | ExceptionGroup: group2</span>
- <span class="go"> +-+---------------- 1 ----------------</span>
- <span class="go"> | RecursionError: 4</span>
- <span class="go"> +------------------------------------</span>
- <span class="gp">>>></span>
- </pre></div>
- </div>
- <p>Note that the exceptions nested in an exception group must be instances,
- not types. This is because in practice the exceptions would typically
- be ones that have already been raised and caught by the program, along
- the following pattern:</p>
- <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="n">excs</span> <span class="o">=</span> <span class="p">[]</span>
- <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>
- <span class="gp">... </span> <span class="k">try</span><span class="p">:</span>
- <span class="gp">... </span> <span class="n">test</span><span class="o">.</span><span class="n">run</span><span class="p">()</span>
- <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>
- <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>
- <span class="gp">...</span>
- <span class="gp">>>> </span><span class="k">if</span> <span class="n">excs</span><span class="p">:</span>
- <span class="gp">... </span> <span class="k">raise</span> <span class="n">ExceptionGroup</span><span class="p">(</span><span class="s2">"Test Failures"</span><span class="p">,</span> <span class="n">excs</span><span class="p">)</span>
- <span class="gp">...</span>
- </pre></div>
- </div>
- </section>
- <section id="enriching-exceptions-with-notes">
- <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>
- <p>When an exception is created in order to be raised, it is usually initialized
- with information that describes the error that has occurred. There are cases
- where it is useful to add information after the exception was caught. For this
- purpose, exceptions have a method <code class="docutils literal notranslate"><span class="pre">add_note(note)</span></code> that accepts a string and
- adds it to the exception’s notes list. The standard traceback rendering
- includes all notes, in the order they were added, after the exception.</p>
- <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="k">try</span><span class="p">:</span>
- <span class="gp">... </span> <span class="k">raise</span> <span class="ne">TypeError</span><span class="p">(</span><span class="s1">'bad type'</span><span class="p">)</span>
- <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>
- <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">'Add some information'</span><span class="p">)</span>
- <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">'Add some more information'</span><span class="p">)</span>
- <span class="gp">... </span> <span class="k">raise</span>
- <span class="gp">...</span>
- <span class="gt">Traceback (most recent call last):</span>
- File <span class="nb">"<stdin>"</span>, line <span class="m">2</span>, in <span class="n"><module></span>
- <span class="gr">TypeError</span>: <span class="n">bad type</span>
- <span class="x">Add some information</span>
- <span class="x">Add some more information</span>
- <span class="gp">>>></span>
- </pre></div>
- </div>
- <p>For example, when collecting exceptions into an exception group, we may want
- to add context information for the individual errors. In the following each
- exception in the group has a note indicating when this error has occurred.</p>
- <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="k">def</span> <span class="nf">f</span><span class="p">():</span>
- <span class="gp">... </span> <span class="k">raise</span> <span class="ne">OSError</span><span class="p">(</span><span class="s1">'operation failed'</span><span class="p">)</span>
- <span class="gp">...</span>
- <span class="gp">>>> </span><span class="n">excs</span> <span class="o">=</span> <span class="p">[]</span>
- <span class="gp">>>> </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>
- <span class="gp">... </span> <span class="k">try</span><span class="p">:</span>
- <span class="gp">... </span> <span class="n">f</span><span class="p">()</span>
- <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>
- <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">'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">'</span><span class="p">)</span>
- <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>
- <span class="gp">...</span>
- <span class="gp">>>> </span><span class="k">raise</span> <span class="n">ExceptionGroup</span><span class="p">(</span><span class="s1">'We have some problems'</span><span class="p">,</span> <span class="n">excs</span><span class="p">)</span>
- <span class="go"> + Exception Group Traceback (most recent call last):</span>
- <span class="go"> | File "<stdin>", line 1, in <module></span>
- <span class="go"> | ExceptionGroup: We have some problems (3 sub-exceptions)</span>
- <span class="go"> +-+---------------- 1 ----------------</span>
- <span class="go"> | Traceback (most recent call last):</span>
- <span class="go"> | File "<stdin>", line 3, in <module></span>
- <span class="go"> | File "<stdin>", line 2, in f</span>
- <span class="go"> | OSError: operation failed</span>
- <span class="go"> | Happened in Iteration 1</span>
- <span class="go"> +---------------- 2 ----------------</span>
- <span class="go"> | Traceback (most recent call last):</span>
- <span class="go"> | File "<stdin>", line 3, in <module></span>
- <span class="go"> | File "<stdin>", line 2, in f</span>
- <span class="go"> | OSError: operation failed</span>
- <span class="go"> | Happened in Iteration 2</span>
- <span class="go"> +---------------- 3 ----------------</span>
- <span class="go"> | Traceback (most recent call last):</span>
- <span class="go"> | File "<stdin>", line 3, in <module></span>
- <span class="go"> | File "<stdin>", line 2, in f</span>
- <span class="go"> | OSError: operation failed</span>
- <span class="go"> | Happened in Iteration 3</span>
- <span class="go"> +------------------------------------</span>
- <span class="gp">>>></span>
- </pre></div>
- </div>
- </section>
- </section>
- <div class="clearer"></div>
- </div>
- </div>
- </div>
- <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
- <div class="sphinxsidebarwrapper">
- <div>
- <h3><a href="../contents.html">Table of Contents</a></h3>
- <ul>
- <li><a class="reference internal" href="#">8. Errors and Exceptions</a><ul>
- <li><a class="reference internal" href="#syntax-errors">8.1. Syntax Errors</a></li>
- <li><a class="reference internal" href="#exceptions">8.2. Exceptions</a></li>
- <li><a class="reference internal" href="#handling-exceptions">8.3. Handling Exceptions</a></li>
- <li><a class="reference internal" href="#raising-exceptions">8.4. Raising Exceptions</a></li>
- <li><a class="reference internal" href="#exception-chaining">8.5. Exception Chaining</a></li>
- <li><a class="reference internal" href="#user-defined-exceptions">8.6. User-defined Exceptions</a></li>
- <li><a class="reference internal" href="#defining-clean-up-actions">8.7. Defining Clean-up Actions</a></li>
- <li><a class="reference internal" href="#predefined-clean-up-actions">8.8. Predefined Clean-up Actions</a></li>
- <li><a class="reference internal" href="#raising-and-handling-multiple-unrelated-exceptions">8.9. Raising and Handling Multiple Unrelated Exceptions</a></li>
- <li><a class="reference internal" href="#enriching-exceptions-with-notes">8.10. Enriching Exceptions with Notes</a></li>
- </ul>
- </li>
- </ul>
- </div>
- <div>
- <h4>Previous topic</h4>
- <p class="topless"><a href="inputoutput.html"
- title="previous chapter"><span class="section-number">7. </span>Input and Output</a></p>
- </div>
- <div>
- <h4>Next topic</h4>
- <p class="topless"><a href="classes.html"
- title="next chapter"><span class="section-number">9. </span>Classes</a></p>
- </div>
- <div role="note" aria-label="source link">
- <h3>This Page</h3>
- <ul class="this-page-menu">
- <li><a href="../bugs.html">Report a Bug</a></li>
- <li>
- <a href="https://github.com/python/cpython/blob/main/Doc/tutorial/errors.rst"
- rel="nofollow">Show Source
- </a>
- </li>
- </ul>
- </div>
- </div>
- </div>
- <div class="clearer"></div>
- </div>
- <div class="related" role="navigation" aria-label="related navigation">
- <h3>Navigation</h3>
- <ul>
- <li class="right" style="margin-right: 10px">
- <a href="../genindex.html" title="General Index"
- >index</a></li>
- <li class="right" >
- <a href="../py-modindex.html" title="Python Module Index"
- >modules</a> |</li>
- <li class="right" >
- <a href="classes.html" title="9. Classes"
- >next</a> |</li>
- <li class="right" >
- <a href="inputoutput.html" title="7. Input and Output"
- >previous</a> |</li>
- <li><img src="../_static/py.svg" alt="python logo" style="vertical-align: middle; margin-top: -1px"/></li>
- <li><a href="https://www.python.org/">Python</a> »</li>
- <li class="switchers">
- <div class="language_switcher_placeholder"></div>
- <div class="version_switcher_placeholder"></div>
- </li>
- <li>
-
- </li>
- <li id="cpython-language-and-version">
- <a href="../index.html">3.12.0 Documentation</a> »
- </li>
- <li class="nav-item nav-item-1"><a href="index.html" >The Python Tutorial</a> »</li>
- <li class="nav-item nav-item-this"><a href=""><span class="section-number">8. </span>Errors and Exceptions</a></li>
- <li class="right">
-
- <div class="inline-search" role="search">
- <form class="inline-search" action="../search.html" method="get">
- <input placeholder="Quick search" aria-label="Quick search" type="search" name="q" />
- <input type="submit" value="Go" />
- </form>
- </div>
- |
- </li>
- <li class="right">
- <label class="theme-selector-label">
- Theme
- <select class="theme-selector" oninput="activateTheme(this.value)">
- <option value="auto" selected>Auto</option>
- <option value="light">Light</option>
- <option value="dark">Dark</option>
- </select>
- </label> |</li>
-
- </ul>
- </div>
- <div class="footer">
- © <a href="../copyright.html">Copyright</a> 2001-2023, Python Software Foundation.
- <br />
- This page is licensed under the Python Software Foundation License Version 2.
- <br />
- Examples, recipes, and other code in the documentation are additionally licensed under the Zero Clause BSD License.
- <br />
- See <a href="/license.html">History and License</a> for more information.<br />
- <br />
- The Python Software Foundation is a non-profit corporation.
- <a href="https://www.python.org/psf/donations/">Please donate.</a>
- <br />
- <br />
- Last updated on Oct 02, 2023.
- <a href="/bugs.html">Found a bug</a>?
- <br />
- Created using <a href="https://www.sphinx-doc.org/">Sphinx</a> 4.5.0.
- </div>
- </body>
- </html>
|