978 lines
82 KiB
HTML
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

<!DOCTYPE html>
<html lang="en" data-content_root="../">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" /><meta name="viewport" content="width=device-width, initial-scale=1" />
<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 havent 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 havent 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 &#8212; Python 3.13.3 documentation</title><meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" type="text/css" href="../_static/pygments.css?v=b86133f3" />
<link rel="stylesheet" type="text/css" href="../_static/pydoctheme.css?v=23252803" />
<link id="pygments_dark_css" media="(prefers-color-scheme: dark)" rel="stylesheet" type="text/css" href="../_static/pygments_dark.css?v=5349f25f" />
<script src="../_static/documentation_options.js?v=5d57ca2d"></script>
<script src="../_static/doctools.js?v=9bcbadda"></script>
<script src="../_static/sphinx_highlight.js?v=dc90522c"></script>
<script src="../_static/sidebar.js"></script>
<link rel="search" type="application/opensearchdescription+xml"
title="Search within Python 3.13.3 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/search-focus.js"></script>
<script type="text/javascript" src="../_static/themetoggle.js"></script>
<script type="text/javascript" src="../_static/rtd_switcher.js"></script>
<meta name="readthedocs-addons-api-version" content="1">
</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="Python 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">
<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> &#187;</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.13.3 Documentation</a> &#187;
</li>
<li class="nav-item nav-item-1"><a href="index.html" accesskey="U">The Python Tutorial</a> &#187;</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" id="search-box" />
<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="Link to this heading"></a></h1>
<p>Until now error messages havent 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="Link to this heading"></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">&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>
File <span class="nb">&quot;&lt;stdin&gt;&quot;</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">&#39;Hello world&#39;</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 little arrows pointing
at the place where the error was detected. Note that this is not always the
place that needs to be fixed. 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 just before it.</p>
<p>The file name (<code class="docutils literal notranslate"><span class="pre">&lt;stdin&gt;</span></code> in our example) and line number are printed so you
know where to look in case the input came from a file.</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="Link to this heading"></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">&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>
<span class="gt">Traceback (most recent call last):</span>
File <span class="nb">&quot;&lt;stdin&gt;&quot;</span>, line <span class="m">1</span>, in <span class="n">&lt;module&gt;</span>
<span class="w"> </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="w"> </span><span class="pm">~^~</span>
<span class="gr">ZeroDivisionError</span>: <span class="n">division by zero</span>
<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>
<span class="gt">Traceback (most recent call last):</span>
File <span class="nb">&quot;&lt;stdin&gt;&quot;</span>, line <span class="m">1</span>, in <span class="n">&lt;module&gt;</span>
<span class="w"> </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="w"> </span><span class="pm">^^^^</span>
<span class="gr">NameError</span>: <span class="n">name &#39;spam&#39; is not defined</span>
<span class="gp">&gt;&gt;&gt; </span><span class="s1">&#39;2&#39;</span> <span class="o">+</span> <span class="mi">2</span>
<span class="gt">Traceback (most recent call last):</span>
File <span class="nb">&quot;&lt;stdin&gt;&quot;</span>, line <span class="m">1</span>, in <span class="n">&lt;module&gt;</span>
<span class="w"> </span><span class="s1">&#39;2&#39;</span> <span class="o">+</span> <span class="mi">2</span>
<span class="w"> </span><span class="pm">~~~~^~~</span>
<span class="gr">TypeError</span>: <span class="n">can only concatenate str (not &quot;int&quot;) 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="Link to this heading"></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 docutils literal notranslate">Control</kbd>-<kbd class="kbd docutils literal notranslate">C</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">&gt;&gt;&gt; </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">&quot;Please enter a number: &quot;</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">&quot;Oops! That was no valid number. Try again...&quot;</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 an error message.</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 matches exceptions which are instances of the
class itself or one of its derived classes (but not the other way around — an
<em>except clause</em> listing a derived class does not match instances of its base classes).
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="w"> </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="w"> </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="w"> </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">&quot;D&quot;</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">&quot;C&quot;</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">&quot;B&quot;</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
exceptions <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">&gt;&gt;&gt; </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">&#39;spam&#39;</span><span class="p">,</span> <span class="s1">&#39;eggs&#39;</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">&#39;x =&#39;</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">&#39;y =&#39;</span><span class="p">,</span> <span class="n">y</span><span class="p">)</span>
<span class="gp">...</span>
<span class="go">&lt;class &#39;Exception&#39;&gt;</span>
<span class="go">(&#39;spam&#39;, &#39;eggs&#39;)</span>
<span class="go">(&#39;spam&#39;, &#39;eggs&#39;)</span>
<span class="go">x = spam</span>
<span class="go">y = eggs</span>
</pre></div>
</div>
<p>The exceptions <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="w"> </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">&#39;myfile.txt&#39;</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">&quot;OS error:&quot;</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">&quot;Could not convert data to an integer.&quot;</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">&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>
<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">&#39;r&#39;</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">&#39;cannot open&#39;</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">&#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>
<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 wasnt 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">&gt;&gt;&gt; </span><span class="k">def</span><span class="w"> </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">&gt;&gt;&gt; </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">&#39;Handling run-time error:&#39;</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="Link to this heading"></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">&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>
<span class="gt">Traceback (most recent call last):</span>
File <span class="nb">&quot;&lt;stdin&gt;&quot;</span>, line <span class="m">1</span>, in <span class="n">&lt;module&gt;</span>
<span class="w"> </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>
<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 &#39;raise ValueError()&#39;</span>
</pre></div>
</div>
<p>If you need to determine whether an exception was raised but dont 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">&gt;&gt;&gt; </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">&#39;HiThere&#39;</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">&#39;An exception flew by!&#39;</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">&quot;&lt;stdin&gt;&quot;</span>, line <span class="m">2</span>, in <span class="n">&lt;module&gt;</span>
<span class="w"> </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>
<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="Link to this heading"></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">&gt;&gt;&gt; </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">&quot;database.sqlite&quot;</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">&quot;unable to handle error&quot;</span><span class="p">)</span>
<span class="gp">...</span>
<span class="gt">Traceback (most recent call last):</span>
File <span class="nb">&quot;&lt;stdin&gt;&quot;</span>, line <span class="m">2</span>, in <span class="n">&lt;module&gt;</span>
<span class="w"> </span><span class="nb">open</span><span class="p">(</span><span class="s2">&quot;database.sqlite&quot;</span><span class="p">)</span>
<span class="w"> </span><span class="pm">~~~~^^^^^^^^^^^^^^^^^^^</span>
<span class="gr">FileNotFoundError</span>: <span class="n">[Errno 2] No such file or directory: &#39;database.sqlite&#39;</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">&quot;&lt;stdin&gt;&quot;</span>, line <span class="m">4</span>, in <span class="n">&lt;module&gt;</span>
<span class="w"> </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>
<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="w"> </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">&gt;&gt;&gt; </span><span class="k">def</span><span class="w"> </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">&gt;&gt;&gt; </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">&#39;Failed to open database&#39;</span><span class="p">)</span> <span class="kn">from</span><span class="w"> </span><span class="nn">exc</span>
<span class="gp">...</span>
<span class="gt">Traceback (most recent call last):</span>
File <span class="nb">&quot;&lt;stdin&gt;&quot;</span>, line <span class="m">2</span>, in <span class="n">&lt;module&gt;</span>
<span class="w"> </span><span class="n">func</span><span class="p">()</span>
<span class="w"> </span><span class="pm">~~~~^^</span>
File <span class="nb">&quot;&lt;stdin&gt;&quot;</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">&quot;&lt;stdin&gt;&quot;</span>, line <span class="m">4</span>, in <span class="n">&lt;module&gt;</span>
<span class="w"> </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="w"> </span><span class="nn">exc</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">&gt;&gt;&gt; </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">&#39;database.sqlite&#39;</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="w"> </span><span class="kc">None</span>
<span class="gp">...</span>
<span class="gt">Traceback (most recent call last):</span>
File <span class="nb">&quot;&lt;stdin&gt;&quot;</span>, line <span class="m">4</span>, in <span class="n">&lt;module&gt;</span>
<span class="w"> </span><span class="k">raise</span> <span class="ne">RuntimeError</span> <span class="kn">from</span><span class="w"> </span><span class="kc">None</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="Link to this heading"></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="Link to this heading"></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">&gt;&gt;&gt; </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">&#39;Goodbye, world!&#39;</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">&quot;&lt;stdin&gt;&quot;</span>, line <span class="m">2</span>, in <span class="n">&lt;module&gt;</span>
<span class="w"> </span><span class="k">raise</span> <span class="ne">KeyboardInterrupt</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>
statements 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> clauses <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> clauses <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">&gt;&gt;&gt; </span><span class="k">def</span><span class="w"> </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">&gt;&gt;&gt; </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">&gt;&gt;&gt; </span><span class="k">def</span><span class="w"> </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">&quot;division by zero!&quot;</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">&quot;result is&quot;</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">&quot;executing finally clause&quot;</span><span class="p">)</span>
<span class="gp">...</span>
<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>
<span class="go">result is 2.0</span>
<span class="go">executing finally clause</span>
<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>
<span class="go">division by zero!</span>
<span class="go">executing finally clause</span>
<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>
<span class="go">executing finally clause</span>
<span class="gt">Traceback (most recent call last):</span>
File <span class="nb">&quot;&lt;stdin&gt;&quot;</span>, line <span class="m">1</span>, in <span class="n">&lt;module&gt;</span>
<span class="w"> </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>
<span class="w"> </span><span class="pm">~~~~~~^^^^^^^^^^</span>
File <span class="nb">&quot;&lt;stdin&gt;&quot;</span>, line <span class="m">3</span>, in <span class="n">divide</span>
<span class="w"> </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="w"> </span><span class="pm">~~^~~</span>
<span class="gr">TypeError</span>: <span class="n">unsupported operand type(s) for /: &#39;str&#39; and &#39;str&#39;</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="Link to this heading"></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">&quot;myfile.txt&quot;</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">&quot;&quot;</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">&quot;myfile.txt&quot;</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">&quot;&quot;</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="Link to this heading"></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">&gt;&gt;&gt; </span><span class="k">def</span><span class="w"> </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">&#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>
<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>
<span class="gp">...</span>
<span class="gp">&gt;&gt;&gt; </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 &quot;&lt;stdin&gt;&quot;, line 1, in &lt;module&gt;</span>
<span class="go"> | f()</span>
<span class="go"> | ~^^</span>
<span class="go"> | File &quot;&lt;stdin&gt;&quot;, line 3, in f</span>
<span class="go"> | raise ExceptionGroup(&#39;there were problems&#39;, excs)</span>
<span class="go"> | ExceptionGroup: there were problems (2 sub-exceptions)</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">&gt;&gt;&gt; </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">&#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>
<span class="gp">...</span>
<span class="go">caught &lt;class &#39;ExceptionGroup&#39;&gt;: e</span>
<span class="gp">&gt;&gt;&gt;</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">&gt;&gt;&gt; </span><span class="k">def</span><span class="w"> </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">&quot;group1&quot;</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">&quot;group2&quot;</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">&gt;&gt;&gt; </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">&quot;There were OSErrors&quot;</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">&quot;There were SystemErrors&quot;</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 &quot;&lt;stdin&gt;&quot;, line 2, in &lt;module&gt;</span>
<span class="go"> | f()</span>
<span class="go"> | ~^^</span>
<span class="go"> | File &quot;&lt;stdin&gt;&quot;, line 2, in f</span>
<span class="go"> | raise ExceptionGroup(</span>
<span class="go"> | ...&lt;12 lines&gt;...</span>
<span class="go"> | )</span>
<span class="go"> | ExceptionGroup: group1 (1 sub-exception)</span>
<span class="go"> +-+---------------- 1 ----------------</span>
<span class="go"> | ExceptionGroup: group2 (1 sub-exception)</span>
<span class="go"> +-+---------------- 1 ----------------</span>
<span class="go"> | RecursionError: 4</span>
<span class="go"> +------------------------------------</span>
<span class="gp">&gt;&gt;&gt;</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">&gt;&gt;&gt; </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">&gt;&gt;&gt; </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">&quot;Test Failures&quot;</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="Link to this heading"></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 exceptions 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">&gt;&gt;&gt; </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">&#39;bad type&#39;</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">&#39;Add some information&#39;</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">&#39;Add some more information&#39;</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">&quot;&lt;stdin&gt;&quot;</span>, line <span class="m">2</span>, in <span class="n">&lt;module&gt;</span>
<span class="w"> </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>
<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">&gt;&gt;&gt;</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">&gt;&gt;&gt; </span><span class="k">def</span><span class="w"> </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">&#39;operation failed&#39;</span><span class="p">)</span>
<span class="gp">...</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">excs</span> <span class="o">=</span> <span class="p">[]</span>
<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>
<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">&#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>
<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">&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>
<span class="go"> + Exception Group Traceback (most recent call last):</span>
<span class="go"> | File &quot;&lt;stdin&gt;&quot;, line 1, in &lt;module&gt;</span>
<span class="go"> | raise ExceptionGroup(&#39;We have some problems&#39;, excs)</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 &quot;&lt;stdin&gt;&quot;, line 3, in &lt;module&gt;</span>
<span class="go"> | f()</span>
<span class="go"> | ~^^</span>
<span class="go"> | File &quot;&lt;stdin&gt;&quot;, line 2, in f</span>
<span class="go"> | raise OSError(&#39;operation failed&#39;)</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 &quot;&lt;stdin&gt;&quot;, line 3, in &lt;module&gt;</span>
<span class="go"> | f()</span>
<span class="go"> | ~^^</span>
<span class="go"> | File &quot;&lt;stdin&gt;&quot;, line 2, in f</span>
<span class="go"> | raise OSError(&#39;operation failed&#39;)</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 &quot;&lt;stdin&gt;&quot;, line 3, in &lt;module&gt;</span>
<span class="go"> | f()</span>
<span class="go"> | ~^^</span>
<span class="go"> | File &quot;&lt;stdin&gt;&quot;, line 2, in f</span>
<span class="go"> | raise OSError(&#39;operation failed&#39;)</span>
<span class="go"> | OSError: operation failed</span>
<span class="go"> | Happened in Iteration 3</span>
<span class="go"> +------------------------------------</span>
<span class="gp">&gt;&gt;&gt;</span>
</pre></div>
</div>
</section>
</section>
<div class="clearer"></div>
</div>
</div>
</div>
<div class="sphinxsidebar" role="navigation" aria-label="Main">
<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 id="sidebarbutton" title="Collapse sidebar">
<span>«</span>
</div>
</div>
<div class="clearer"></div>
</div>
<div class="related" role="navigation" aria-label="Related">
<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> &#187;</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.13.3 Documentation</a> &#187;
</li>
<li class="nav-item nav-item-1"><a href="index.html" >The Python Tutorial</a> &#187;</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" id="search-box" />
<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">
&copy;
<a href="../copyright.html">
Copyright
</a>
2001-2025, 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 Apr 08, 2025 (14:33 UTC).
<a href="/bugs.html">Found a bug</a>?
<br />
Created using <a href="https://www.sphinx-doc.org/">Sphinx</a> 8.2.3.
</div>
</body>
</html>