<div class="section" id="the-try-statement">
<span id="finally"></span><span id="except"></span><span id="try"></span><h2>The <a class="reference internal" href="#try"><tt class="xref std std-keyword docutils literal"><span class="pre">try</span></tt></a> statement</h2>
<span class="target" id="index-10"></span><p id="index-11">The <a class="reference internal" href="#try"><tt class="xref std std-keyword docutils literal"><span class="pre">try</span></tt></a> statement specifies exception handlers and/or cleanup code
for a group of statements:</p>
<pre>
<strong id="grammar-token-try_stmt">try_stmt </strong> ::=  try1_stmt | try2_stmt
<strong id="grammar-token-try1_stmt">try1_stmt</strong> ::=  &quot;try&quot; &quot;:&quot; <a class="reference internal" href="#grammar-token-suite"><tt class="xref docutils literal"><span class="pre">suite</span></tt></a>
               (&quot;except&quot; [<a class="reference internal" href="expressions.html#grammar-token-expression"><tt class="xref docutils literal"><span class="pre">expression</span></tt></a> [&quot;as&quot; <a class="reference internal" href="lexical_analysis.html#grammar-token-identifier"><tt class="xref docutils literal"><span class="pre">identifier</span></tt></a>]] &quot;:&quot; <a class="reference internal" href="#grammar-token-suite"><tt class="xref docutils literal"><span class="pre">suite</span></tt></a>)+
               [&quot;else&quot; &quot;:&quot; <a class="reference internal" href="#grammar-token-suite"><tt class="xref docutils literal"><span class="pre">suite</span></tt></a>]
               [&quot;finally&quot; &quot;:&quot; <a class="reference internal" href="#grammar-token-suite"><tt class="xref docutils literal"><span class="pre">suite</span></tt></a>]
<strong id="grammar-token-try2_stmt">try2_stmt</strong> ::=  &quot;try&quot; &quot;:&quot; <a class="reference internal" href="#grammar-token-suite"><tt class="xref docutils literal"><span class="pre">suite</span></tt></a>
               &quot;finally&quot; &quot;:&quot; <a class="reference internal" href="#grammar-token-suite"><tt class="xref docutils literal"><span class="pre">suite</span></tt></a>
</pre>
<p>The <a class="reference internal" href="#except"><tt class="xref std std-keyword docutils literal"><span class="pre">except</span></tt></a> clause(s) specify one or more exception handlers. When no
exception occurs in the <a class="reference internal" href="#try"><tt class="xref std std-keyword docutils literal"><span class="pre">try</span></tt></a> clause, no exception handler is executed.
When an exception occurs in the <a class="reference internal" href="#try"><tt class="xref std std-keyword docutils literal"><span class="pre">try</span></tt></a> suite, a search for an exception
handler is started.  This search inspects the except clauses in turn until one
is found that matches the exception.  An expression-less except clause, if
present, must be last; it matches any exception.  For an except clause with an
expression, that expression is evaluated, and the clause matches the exception
if the resulting object is &#8220;compatible&#8221; with the exception.  An object is
compatible with an exception if it is the class or a base class of the exception
object or a tuple containing an item compatible with the exception.</p>
<p>If no except clause matches the exception, the search for an exception handler
continues in the surrounding code and on the invocation stack.  <a class="footnote-reference" href="#id5" id="id1">[1]</a></p>
<p>If the evaluation of an expression in the header of an except clause raises an
exception, the original search for a handler is canceled and a search starts for
the new exception in the surrounding code and on the call stack (it is treated
as if the entire <a class="reference internal" href="#try"><tt class="xref std std-keyword docutils literal"><span class="pre">try</span></tt></a> statement raised the exception).</p>
<p>When a matching except clause is found, the exception is assigned to the target
specified after the <a class="reference internal" href="#as"><tt class="xref std std-keyword docutils literal"><span class="pre">as</span></tt></a> keyword in that except clause, if present, and
the except clause&#8217;s suite is executed.  All except clauses must have an
executable block.  When the end of this block is reached, execution continues
normally after the entire try statement.  (This means that if two nested
handlers exist for the same exception, and the exception occurs in the try
clause of the inner handler, the outer handler will not handle the exception.)</p>
<p>When an exception has been assigned using <tt class="docutils literal"><span class="pre">as</span> <span class="pre">target</span></tt>, it is cleared at the
end of the except clause.  This is as if</p>
<div class="highlight-python3"><div class="highlight"><pre><span class="k">except</span> <span class="n">E</span> <span class="k">as</span> <span class="n">N</span><span class="p">:</span>
    <span class="n">foo</span>
</pre></div>
</div>
<p>was translated to</p>
<div class="highlight-python3"><div class="highlight"><pre><span class="k">except</span> <span class="n">E</span> <span class="k">as</span> <span class="n">N</span><span class="p">:</span>
    <span class="k">try</span><span class="p">:</span>
        <span class="n">foo</span>
    <span class="k">finally</span><span class="p">:</span>
        <span class="k">del</span> <span class="n">N</span>
</pre></div>
</div>
<p>This means the exception must be assigned to a different name to be able to
refer to it after the except clause.  Exceptions are cleared because with the
traceback attached to them, they form a reference cycle with the stack frame,
keeping all locals in that frame alive until the next garbage collection occurs.</p>
<p id="index-12">Before an except clause&#8217;s suite is executed, details about the exception are
stored in the <a class="reference internal" href="../library/sys.html#module-sys" title="sys: Access system-specific parameters and functions."><tt class="xref py py-mod docutils literal"><span class="pre">sys</span></tt></a> module and can be accessed via <a class="reference internal" href="../library/sys.html#sys.exc_info" title="sys.exc_info"><tt class="xref py py-func docutils literal"><span class="pre">sys.exc_info()</span></tt></a>.
<a class="reference internal" href="../library/sys.html#sys.exc_info" title="sys.exc_info"><tt class="xref py py-func docutils literal"><span class="pre">sys.exc_info()</span></tt></a> returns a 3-tuple consisting of the exception class, the
exception instance and a traceback object (see section <a class="reference internal" href="datamodel.html#types"><em>The standard type hierarchy</em></a>) identifying
the point in the program where the exception occurred.  <a class="reference internal" href="../library/sys.html#sys.exc_info" title="sys.exc_info"><tt class="xref py py-func docutils literal"><span class="pre">sys.exc_info()</span></tt></a>
values are restored to their previous values (before the call) when returning
from a function that handled an exception.</p>
<p id="index-13">The optional <a class="reference internal" href="#else"><tt class="xref std std-keyword docutils literal"><span class="pre">else</span></tt></a> clause is executed if and when control flows off
the end of the <a class="reference internal" href="#try"><tt class="xref std std-keyword docutils literal"><span class="pre">try</span></tt></a> clause. <a class="footnote-reference" href="#id6" id="id2">[2]</a> Exceptions in the <a class="reference internal" href="#else"><tt class="xref std std-keyword docutils literal"><span class="pre">else</span></tt></a>
clause are not handled by the preceding <a class="reference internal" href="#except"><tt class="xref std std-keyword docutils literal"><span class="pre">except</span></tt></a> clauses.</p>
<p id="index-14">If <a class="reference internal" href="#finally"><tt class="xref std std-keyword docutils literal"><span class="pre">finally</span></tt></a> is present, it specifies a &#8216;cleanup&#8217; handler.  The
<a class="reference internal" href="#try"><tt class="xref std std-keyword docutils literal"><span class="pre">try</span></tt></a> clause is executed, including any <a class="reference internal" href="#except"><tt class="xref std std-keyword docutils literal"><span class="pre">except</span></tt></a> and
<a class="reference internal" href="#else"><tt class="xref std std-keyword docutils literal"><span class="pre">else</span></tt></a> clauses.  If an exception occurs in any of the clauses and is
not handled, the exception is temporarily saved. The <a class="reference internal" href="#finally"><tt class="xref std std-keyword docutils literal"><span class="pre">finally</span></tt></a> clause
is executed.  If there is a saved exception it is re-raised at the end of the
<a class="reference internal" href="#finally"><tt class="xref std std-keyword docutils literal"><span class="pre">finally</span></tt></a> clause.  If the <a class="reference internal" href="#finally"><tt class="xref std std-keyword docutils literal"><span class="pre">finally</span></tt></a> clause raises another
exception, the saved exception is set as the context of the new exception.
If the <a class="reference internal" href="#finally"><tt class="xref std std-keyword docutils literal"><span class="pre">finally</span></tt></a> clause executes a <a class="reference internal" href="simple_stmts.html#return"><tt class="xref std std-keyword docutils literal"><span class="pre">return</span></tt></a> or <a class="reference internal" href="simple_stmts.html#break"><tt class="xref std std-keyword docutils literal"><span class="pre">break</span></tt></a>
statement, the saved exception is discarded:</p>
<div class="highlight-python3"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="k">def</span> <span class="nf">f</span><span class="p">():</span>
<span class="gp">... </span>    <span class="k">try</span><span class="p">:</span>
<span class="gp">... </span>        <span class="mi">1</span><span class="o">/</span><span class="mi">0</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="mi">42</span>
<span class="gp">...</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">f</span><span class="p">()</span>
<span class="go">42</span>
</pre></div>
</div>
<p>The exception information is not available to the program during execution of
the <a class="reference internal" href="#finally"><tt class="xref std std-keyword docutils literal"><span class="pre">finally</span></tt></a> clause.</p>
<p id="index-15">When a <a class="reference internal" href="simple_stmts.html#return"><tt class="xref std std-keyword docutils literal"><span class="pre">return</span></tt></a>, <a class="reference internal" href="simple_stmts.html#break"><tt class="xref std std-keyword docutils literal"><span class="pre">break</span></tt></a> or <a class="reference internal" href="simple_stmts.html#continue"><tt class="xref std std-keyword docutils literal"><span class="pre">continue</span></tt></a> statement is
executed in the <a class="reference internal" href="#try"><tt class="xref std std-keyword docutils literal"><span class="pre">try</span></tt></a> suite of a <a class="reference internal" href="#try"><tt class="xref std std-keyword docutils literal"><span class="pre">try</span></tt></a>...<a class="reference internal" href="#finally"><tt class="xref std std-keyword docutils literal"><span class="pre">finally</span></tt></a>
statement, the <a class="reference internal" href="#finally"><tt class="xref std std-keyword docutils literal"><span class="pre">finally</span></tt></a> clause is also executed &#8216;on the way out.&#8217; A
<a class="reference internal" href="simple_stmts.html#continue"><tt class="xref std std-keyword docutils literal"><span class="pre">continue</span></tt></a> statement is illegal in the <a class="reference internal" href="#finally"><tt class="xref std std-keyword docutils literal"><span class="pre">finally</span></tt></a> clause. (The
reason is a problem with the current implementation &#8212; this restriction may be
lifted in the future).</p>
<p>The return value of a function is determined by the last <a class="reference internal" href="simple_stmts.html#return"><tt class="xref std std-keyword docutils literal"><span class="pre">return</span></tt></a>
statement executed.  Since the <a class="reference internal" href="#finally"><tt class="xref std std-keyword docutils literal"><span class="pre">finally</span></tt></a> clause always executes, a
<a class="reference internal" href="simple_stmts.html#return"><tt class="xref std std-keyword docutils literal"><span class="pre">return</span></tt></a> statement executed in the <a class="reference internal" href="#finally"><tt class="xref std std-keyword docutils literal"><span class="pre">finally</span></tt></a> clause will
always be the last one executed:</p>
<div class="highlight-python3"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="k">def</span> <span class="nf">foo</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="s">&#39;try&#39;</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="s">&#39;finally&#39;</span>
<span class="gp">...</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">foo</span><span class="p">()</span>
<span class="go">&#39;finally&#39;</span>
</pre></div>
</div>
<p>Additional information on exceptions can be found in section <a class="reference internal" href="executionmodel.html#exceptions"><em>Exceptions</em></a>,
and information on using the <a class="reference internal" href="simple_stmts.html#raise"><tt class="xref std std-keyword docutils literal"><span class="pre">raise</span></tt></a> statement to generate exceptions
may be found in section <a class="reference internal" href="simple_stmts.html#raise"><em>The raise statement</em></a>.</p>
</div>
