<!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 — 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> 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> » </ul> </div> <p> </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 d’exceptions permet de continuer le calcul sachant qu’une 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">>>> </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">"<stdin>"</span>, line <span class="m">1</span>, in <span class="n"><module></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">>>> </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">"Pas le bon type"</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">>>> </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">"une string"</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">>></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 d’appel 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 d’appels, elle se lit de bas en haut. Il est possible de provoquer cette pile d’appels.</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">s’exercer à lire une pile d’appels 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 d’appels sans savoir précisément ce que l’on fait, et remonter une autre exception</p> </div> <p>Exemple :</p> <div class="highlight-default"><div class="highlight"><pre><span></span><span class="gp">>>> </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">"pas le bon type"</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">"ok"</span> <span class="gp">...</span> <span class="gp">>>> </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">"c'est "</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">"on a une autre exception là"</span><span class="p">)</span> <span class="gp">...</span> <span class="gp">>>> </span><span class="k">try</span><span class="p">:</span> <span class="gp">... </span> <span class="n">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">>>></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 d’exceptions <em>dans la vraie vie</em>:</p> <div class="highlight-default"><div class="highlight"><pre><span></span><span class="s2">"user defined exceptions"</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">"attempt to access to an option with a property that is not allowed"</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">"""attempt to change an option'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"""</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">"""context needed but not given</span> <span class="sd"> """</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">"duplicate options are present in a single config"</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">"""a recursive loop occurs in the requirements tree</span> <span class="sd"> requires</span> <span class="sd"> """</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">"problem with a slave's value length"</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">"no uniq value in _NameSpace"</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é. C’est assez agréable mais le réserver pour la gestion d’une 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">>>> </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> | <!-- 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> » </ul> </div> <div class="footer" role="contentinfo"> © Copyright 2015, cadoles (www.cadoles.com). Créé avec <a href="http://sphinx-doc.org/">Sphinx</a> 1.6.7. </div> </body> </html>