formations/python/python3/fr/_build/html/exceptions.html
2018-08-21 10:25:44 +02:00

343 lines
22 KiB
HTML
Raw Blame History

This file contains invisible Unicode characters

This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

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 PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="fr">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Le style de programmation par exceptions &#8212; Documentation Formation Python 1</title>
<link rel="stylesheet" href="_static/classic.css" type="text/css" />
<link rel="stylesheet" href="_static/pygments.css" type="text/css" />
<script type="text/javascript">
var DOCUMENTATION_OPTIONS = {
URL_ROOT: './',
VERSION: '1',
COLLAPSE_INDEX: false,
FILE_SUFFIX: '.html',
HAS_SOURCE: true,
SOURCELINK_SUFFIX: '.txt'
};
</script>
<script type="text/javascript" src="_static/jquery.js"></script>
<script type="text/javascript" src="_static/underscore.js"></script>
<script type="text/javascript" src="_static/doctools.js"></script>
<script type="text/javascript" src="_static/translations.js"></script>
<link rel="index" title="Index" href="genindex.html" />
<link rel="search" title="Recherche" href="search.html" />
<link rel="next" title="Les design patterns" href="DesignPatterns.html" />
<link rel="prev" title="Programmation python courante" href="specialmethods.html" />
</head>
<body>
<div style="background-color: white; text-align: left; padding: 10px 10px 15px 15px">
<table><tr><td>
<img src="_static/sphinx.png" alt="logo" />
</td><td>
<h1>&nbsp; &nbsp; Programmation python</h1>
</td></tr></table>
</div>
<div class="related" role="navigation" aria-label="related navigation">
<h3>Navigation</h3>
<ul>
<li class="right" style="margin-right: 10px">
<a href="genindex.html" title="Index général"
accesskey="I">index</a></li>
<li class="right" >
<a href="py-modindex.html" title="Index des modules Python"
>modules</a> |</li>
<li class="right" >
<a href="DesignPatterns.html" title="Les design patterns"
accesskey="N">suivant</a> |</li>
<li class="right" >
<a href="specialmethods.html" title="Programmation python courante"
accesskey="P">précédent</a> |</li>
<a href="index.html">Programmation python </a> &raquo;
</ul>
</div>
<p>&nbsp;</p>
<div class="document">
<div class="documentwrapper">
<div class="bodywrapper">
<div class="body" role="main">
<div class="section" id="le-style-de-programmation-par-exceptions">
<h1>Le style de programmation par exceptions<a class="headerlink" href="#le-style-de-programmation-par-exceptions" title="Lien permanent vers ce titre"></a></h1>
<dl class="glossary docutils">
<dt id="term-exception">Exception</dt>
<dd>Les exceptions permettent de récupérer des situations où le calcul ne peut pas se poursuivre.
Dans ces cas, un récupérateur dexceptions permet de continuer le calcul
sachant quune des branches a échoué.</dd>
</dl>
<p>Exemple d”<a class="reference internal" href="#term-exception"><span class="xref std std-term">exception</span></a></p>
<div class="highlight-default"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="k">assert</span> <span class="mi">2</span> <span class="o">==</span> <span class="mi">1</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="gr">AssertionError</span>
</pre></div>
</div>
<div class="section" id="la-regle-du-samourai">
<h2>La règle du samouraï<a class="headerlink" href="#la-regle-du-samourai" title="Lien permanent vers ce titre"></a></h2>
<div class="admonition important">
<p class="first admonition-title">Important</p>
<p class="last">règle du Samouraï : une fonction doit renvoyer le résultat escompté
ou bien lever une exception</p>
</div>
<div class="highlight-default"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="k">def</span> <span class="nf">function_raise</span><span class="p">(</span><span class="n">x</span><span class="p">):</span>
<span class="gp">... </span> <span class="k">if</span> <span class="ow">not</span> <span class="nb">type</span><span class="p">(</span><span class="n">x</span><span class="p">)</span> <span class="o">==</span> <span class="nb">int</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="s2">&quot;Pas le bon type&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="k">return</span> <span class="n">x</span> <span class="o">+</span> <span class="mi">1</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">e</span> <span class="o">=</span> <span class="n">function_raise</span><span class="p">(</span><span class="s2">&quot;une string&quot;</span><span class="p">)</span>
<span class="gp">... </span><span class="k">except</span> <span class="ne">TypeError</span><span class="p">,</span> <span class="n">e</span><span class="p">:</span>
<span class="gp">... </span> <span class="nb">print</span> <span class="n">e</span>
<span class="gp">...</span>
<span class="go">Pas le bon type</span>
<span class="go">&gt;&gt;</span>
</pre></div>
</div>
<ul class="simple">
<li>la fonction doit renvoyer des valeurs du même type (ou bien <code class="docutils literal"><span class="pre">None</span></code>)</li>
<li>la fonction doit lever une exception appropriée</li>
</ul>
</div>
<div class="section" id="utiliser-la-pile-d-appel-pour-debugger">
<h2>utiliser la pile dappel pour débugger<a class="headerlink" href="#utiliser-la-pile-d-appel-pour-debugger" title="Lien permanent vers ce titre"></a></h2>
<p>Utiliser la pile dappels, elle se lit de bas en haut. Il est possible de
provoquer cette pile dappels.</p>
<div class="highlight-default"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">traceback</span>
<span class="n">traceback</span><span class="o">.</span><span class="n">print_exc</span><span class="p">()</span>
</pre></div>
</div>
<div class="admonition-todo admonition" id="index-0">
<p class="first admonition-title">À faire</p>
<p class="last">sexercer à lire une pile dappels un peu complexe.</p>
</div>
<p>Traiter une exception avec</p>
<div class="highlight-default"><div class="highlight"><pre><span></span><span class="k">try</span><span class="p">:</span>
<span class="o">...</span>
<span class="k">except</span><span class="p">:</span>
<span class="kn">import</span> <span class="nn">traceback</span>
<span class="n">traceback</span><span class="o">.</span><span class="n">print_exc</span><span class="p">()</span>
<span class="k">else</span><span class="p">:</span>
<span class="n">bla</span> <span class="n">bla</span>
<span class="k">finally</span><span class="p">:</span>
<span class="n">bla</span> <span class="n">bla</span>
</pre></div>
</div>
<div class="admonition attention">
<p class="first admonition-title">Attention</p>
<p class="last">ne <strong>jamais</strong> briser la pile dappels sans savoir précisément
ce que lon fait, et remonter une autre exception</p>
</div>
<p>Exemple :</p>
<div class="highlight-default"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="k">def</span> <span class="nf">function</span><span class="p">(</span><span class="n">x</span><span class="p">):</span>
<span class="gp">... </span> <span class="k">if</span> <span class="n">x</span> <span class="o">==</span> <span class="mi">1</span><span class="p">:</span> <span class="k">raise</span> <span class="ne">TypeError</span><span class="p">(</span><span class="s2">&quot;pas le bon type&quot;</span><span class="p">)</span>
<span class="gp">... </span> <span class="k">else</span><span class="p">:</span> <span class="k">return</span> <span class="s2">&quot;ok&quot;</span>
<span class="gp">...</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">def</span> <span class="nf">function2</span><span class="p">(</span><span class="n">x</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="s2">&quot;c&#39;est &quot;</span> <span class="o">+</span> <span class="n">function</span><span class="p">(</span><span class="n">x</span><span class="p">)</span>
<span class="gp">... </span> <span class="k">except</span> <span class="ne">TypeError</span><span class="p">,</span> <span class="n">e</span><span class="p">:</span>
<span class="gp">... </span> <span class="k">raise</span> <span class="ne">AssertionError</span><span class="p">(</span><span class="s2">&quot;on a une autre exception là&quot;</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">function2</span><span class="p">(</span><span class="mi">1</span><span class="p">)</span>
<span class="gp">... </span><span class="k">except</span> <span class="ne">Exception</span><span class="p">,</span> <span class="n">e</span><span class="p">:</span>
<span class="gp">... </span> <span class="nb">print</span> <span class="n">e</span>
<span class="gp">...</span>
<span class="go">on a une autre exception là</span>
<span class="go">&gt;&gt;&gt;</span>
</pre></div>
</div>
<p>Le raise (ou le re-raise) est souvent utilisé pour lever une exception métier
et cacher une exception système de bas niveau.</p>
<p>exemple:</p>
<div class="highlight-default"><div class="highlight"><pre><span></span><span class="k">try</span><span class="p">:</span>
<span class="n">add_s</span><span class="p">(</span><span class="n">dn</span><span class="p">,</span> <span class="n">listdata</span><span class="p">)</span>
<span class="k">except</span> <span class="n">ldap</span><span class="o">.</span><span class="n">LDAPError</span><span class="p">,</span> <span class="n">err</span><span class="p">:</span>
<span class="k">raise</span> <span class="n">MyOwnError</span><span class="p">(</span><span class="n">msg</span> <span class="o">+</span> <span class="nb">str</span><span class="p">(</span><span class="n">err</span><span class="p">))</span>
<span class="k">except</span> <span class="ne">Exception</span><span class="p">:</span>
<span class="k">pass</span>
</pre></div>
</div>
<div class="admonition-todo admonition" id="index-1">
<p class="first admonition-title">À faire</p>
<p class="last">dans quel cas entrons-nous dans le <code class="docutils literal"><span class="pre">else</span></code> ? dans le <code class="docutils literal"><span class="pre">finally</span></code> ?</p>
</div>
<div class="admonition-todo admonition" id="index-2">
<p class="first admonition-title">À faire</p>
<p class="last">créer des exceptions métier</p>
</div>
<p>exemple dexceptions <em>dans la vraie vie</em>:</p>
<div class="highlight-default"><div class="highlight"><pre><span></span><span class="s2">&quot;user defined exceptions&quot;</span>
<span class="c1"># Exceptions for an Option</span>
<span class="k">class</span> <span class="nc">PropertiesOptionError</span><span class="p">(</span><span class="ne">AttributeError</span><span class="p">):</span>
<span class="s2">&quot;attempt to access to an option with a property that is not allowed&quot;</span>
<span class="k">def</span> <span class="nf">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">msg</span><span class="p">,</span> <span class="n">proptype</span><span class="p">):</span>
<span class="bp">self</span><span class="o">.</span><span class="n">proptype</span> <span class="o">=</span> <span class="n">proptype</span>
<span class="nb">super</span><span class="p">(</span><span class="n">PropertiesOptionError</span><span class="p">,</span> <span class="bp">self</span><span class="p">)</span><span class="o">.</span><span class="fm">__init__</span><span class="p">(</span><span class="n">msg</span><span class="p">)</span>
<span class="c1">#____________________________________________________________</span>
<span class="c1"># Exceptions for a Config</span>
<span class="k">class</span> <span class="nc">ConfigError</span><span class="p">(</span><span class="ne">Exception</span><span class="p">):</span>
<span class="sd">&quot;&quot;&quot;attempt to change an option&#39;s owner without a value</span>
<span class="sd"> or in case of `_cfgimpl_descr` is None</span>
<span class="sd"> or if a calculation cannot be carried out&quot;&quot;&quot;</span>
<span class="k">pass</span>
<span class="k">class</span> <span class="nc">ContextError</span><span class="p">(</span><span class="ne">Exception</span><span class="p">):</span>
<span class="sd">&quot;&quot;&quot;context needed but not given</span>
<span class="sd"> &quot;&quot;&quot;</span>
<span class="k">pass</span>
<span class="k">class</span> <span class="nc">ConflictError</span><span class="p">(</span><span class="ne">Exception</span><span class="p">):</span>
<span class="s2">&quot;duplicate options are present in a single config&quot;</span>
<span class="k">pass</span>
<span class="c1">#____________________________________________________________</span>
<span class="c1"># miscellaneous exceptions</span>
<span class="k">class</span> <span class="nc">RequirementError</span><span class="p">(</span><span class="ne">Exception</span><span class="p">):</span>
<span class="sd">&quot;&quot;&quot;a recursive loop occurs in the requirements tree</span>
<span class="sd"> requires</span>
<span class="sd"> &quot;&quot;&quot;</span>
<span class="k">pass</span>
<span class="k">class</span> <span class="nc">SlaveError</span><span class="p">(</span><span class="ne">Exception</span><span class="p">):</span>
<span class="s2">&quot;problem with a slave&#39;s value length&quot;</span>
<span class="k">pass</span>
<span class="k">class</span> <span class="nc">ConstError</span><span class="p">(</span><span class="ne">TypeError</span><span class="p">):</span>
<span class="s2">&quot;no uniq value in _NameSpace&quot;</span>
<span class="k">pass</span>
</pre></div>
</div>
<p>Créer le plus possible ses propres exceptions spécifiques au programme
La programmation par exception peut vite devenir un style de programmation
très utilisé. Cest assez agréable mais le réserver pour la gestion dune situation
particulière, que ça reste une intervention pour les cas non gérés par le programme
(en général).</p>
</div>
<div class="section" id="les-exceptions-imbriquees">
<h2>Les exceptions imbriquées<a class="headerlink" href="#les-exceptions-imbriquees" title="Lien permanent vers ce titre"></a></h2>
<div class="highlight-default"><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="n">ma_func</span><span class="p">()</span>
<span class="gp">... </span><span class="k">except</span> <span class="ne">TypeError</span><span class="p">,</span> <span class="n">e</span><span class="p">:</span>
<span class="gp">... </span> <span class="n">do_something</span><span class="p">()</span>
<span class="gp">... </span><span class="k">except</span> <span class="ne">Exception</span><span class="p">,</span> <span class="n">e</span><span class="p">:</span>
<span class="gp">... </span> <span class="n">do_somethin_else</span><span class="p">()</span>
<span class="gp">...</span>
</pre></div>
</div>
<p>Exemple de programme utilisant massivement la programmation par exceptions :
<a class="reference external" href="http://tiramisu.labs.libre-entreprise.org/">tiramisu</a></p>
</div>
<div class="section" id="la-hierarchie-des-exceptions">
<h2>La hiérarchie des exceptions<a class="headerlink" href="#la-hierarchie-des-exceptions" title="Lien permanent vers ce titre"></a></h2>
<p>Extrait de la documentation officielle:</p>
<div class="highlight-default"><div class="highlight"><pre><span></span><span class="ne">BaseException</span>
<span class="o">+--</span> <span class="ne">SystemExit</span>
<span class="o">+--</span> <span class="ne">KeyboardInterrupt</span>
<span class="o">+--</span> <span class="ne">GeneratorExit</span>
<span class="o">+--</span> <span class="ne">Exception</span>
<span class="o">+--</span> <span class="ne">StopIteration</span>
<span class="o">+--</span> <span class="n">StandardError</span>
<span class="o">|</span> <span class="o">+--</span> <span class="ne">BufferError</span>
<span class="o">|</span> <span class="o">+--</span> <span class="ne">ArithmeticError</span>
<span class="o">|</span> <span class="o">|</span> <span class="o">+--</span> <span class="ne">FloatingPointError</span>
<span class="o">|</span> <span class="o">|</span> <span class="o">+--</span> <span class="ne">OverflowError</span>
<span class="o">|</span> <span class="o">|</span> <span class="o">+--</span> <span class="ne">ZeroDivisionError</span>
<span class="o">|</span> <span class="o">+--</span> <span class="ne">AssertionError</span>
<span class="o">|</span> <span class="o">+--</span> <span class="ne">AttributeError</span>
<span class="o">|</span> <span class="o">+--</span> <span class="ne">EnvironmentError</span>
<span class="o">|</span> <span class="o">|</span> <span class="o">+--</span> <span class="ne">IOError</span>
<span class="o">|</span> <span class="o">|</span> <span class="o">+--</span> <span class="ne">OSError</span>
<span class="o">|</span> <span class="o">|</span> <span class="o">+--</span> <span class="ne">WindowsError</span> <span class="p">(</span><span class="n">Windows</span><span class="p">)</span>
<span class="o">|</span> <span class="o">|</span> <span class="o">+--</span> <span class="ne">VMSError</span> <span class="p">(</span><span class="n">VMS</span><span class="p">)</span>
<span class="o">|</span> <span class="o">+--</span> <span class="ne">EOFError</span>
<span class="o">|</span> <span class="o">+--</span> <span class="ne">ImportError</span>
<span class="o">|</span> <span class="o">+--</span> <span class="ne">LookupError</span>
<span class="o">|</span> <span class="o">|</span> <span class="o">+--</span> <span class="ne">IndexError</span>
<span class="o">|</span> <span class="o">|</span> <span class="o">+--</span> <span class="ne">KeyError</span>
<span class="o">|</span> <span class="o">+--</span> <span class="ne">MemoryError</span>
<span class="o">|</span> <span class="o">+--</span> <span class="ne">NameError</span>
<span class="o">|</span> <span class="o">|</span> <span class="o">+--</span> <span class="ne">UnboundLocalError</span>
<span class="o">|</span> <span class="o">+--</span> <span class="ne">ReferenceError</span>
<span class="o">|</span> <span class="o">+--</span> <span class="ne">RuntimeError</span>
<span class="o">|</span> <span class="o">|</span> <span class="o">+--</span> <span class="ne">NotImplementedError</span>
<span class="o">|</span> <span class="o">+--</span> <span class="ne">SyntaxError</span>
<span class="o">|</span> <span class="o">|</span> <span class="o">+--</span> <span class="ne">IndentationError</span>
<span class="o">|</span> <span class="o">|</span> <span class="o">+--</span> <span class="ne">TabError</span>
<span class="o">|</span> <span class="o">+--</span> <span class="ne">SystemError</span>
<span class="o">|</span> <span class="o">+--</span> <span class="ne">TypeError</span>
<span class="o">|</span> <span class="o">+--</span> <span class="ne">ValueError</span>
<span class="o">|</span> <span class="o">+--</span> <span class="ne">UnicodeError</span>
<span class="o">|</span> <span class="o">+--</span> <span class="ne">UnicodeDecodeError</span>
<span class="o">|</span> <span class="o">+--</span> <span class="ne">UnicodeEncodeError</span>
<span class="o">|</span> <span class="o">+--</span> <span class="ne">UnicodeTranslateError</span>
<span class="o">+--</span> <span class="ne">Warning</span>
<span class="o">+--</span> <span class="ne">DeprecationWarning</span>
<span class="o">+--</span> <span class="ne">PendingDeprecationWarning</span>
<span class="o">+--</span> <span class="ne">RuntimeWarning</span>
<span class="o">+--</span> <span class="ne">SyntaxWarning</span>
<span class="o">+--</span> <span class="ne">UserWarning</span>
<span class="o">+--</span> <span class="ne">FutureWarning</span>
<span class="o">+--</span> <span class="ne">ImportWarning</span>
<span class="o">+--</span> <span class="ne">UnicodeWarning</span>
<span class="o">+--</span> <span class="ne">BytesWarning</span>
</pre></div>
</div>
</div>
</div>
</div>
</div>
</div>
<div style="background-color: white; text-align: left; padding: 10px 10px 15px 15px">
<a href="search.html"> Recherche</a> | &nbsp;
<!-- a href="genindex.html"> Genindex</a-->
</div>
<div class="clearer"></div>
</div>
<div class="related" role="navigation" aria-label="related navigation">
<h3>Navigation</h3>
<ul>
<li class="right" style="margin-right: 10px">
<a href="genindex.html" title="Index général"
>index</a></li>
<li class="right" >
<a href="py-modindex.html" title="Index des modules Python"
>modules</a> |</li>
<li class="right" >
<a href="DesignPatterns.html" title="Les design patterns"
>suivant</a> |</li>
<li class="right" >
<a href="specialmethods.html" title="Programmation python courante"
>précédent</a> |</li>
<a href="index.html">Programmation python </a> &raquo;
</ul>
</div>
<div class="footer" role="contentinfo">
&#169; Copyright 2015, cadoles (www.cadoles.com).
Créé avec <a href="http://sphinx-doc.org/">Sphinx</a> 1.6.7.
</div>
</body>
</html>