Popular recipes tagged "exception"http://code.activestate.com/recipes/tags/exception/popular/2017-06-25T17:17:43-07:00ActiveState Code RecipesGuard against an exception in the wrong place (Python) 2017-06-25T17:17:43-07:00Steven D'Apranohttp://code.activestate.com/recipes/users/4172944/http://code.activestate.com/recipes/580808-guard-against-an-exception-in-the-wrong-place/ <p style="color: grey"> Python recipe 580808 by <a href="/recipes/users/4172944/">Steven D'Aprano</a> (<a href="/recipes/tags/context/">context</a>, <a href="/recipes/tags/exception/">exception</a>, <a href="/recipes/tags/guard/">guard</a>, <a href="/recipes/tags/manager/">manager</a>). Revision 2. </p> <p>Sometimes exception handling can obscure bugs unless you guard against a particular exception occurring in a certain place. One example is that <a href="https://www.python.org/dev/peps/pep-0479/">accidentally raising <code>StopIteration</code> inside a generator</a> will halt the generator instead of displaying a traceback. That was solved by PEP 479, which automatically has such <code>StopIteration</code> exceptions change to <code>RuntimeError</code>. See the discussion below for further examples.</p> <p>Here is a class which can be used as either a decorator or context manager for guarding against the given exceptions. It takes an exception (or a tuple of exceptions) as argument, and if the wrapped code raises that exception, it is re-raised as another exception type (by default <code>RuntimeError</code>).</p> <p>For example:</p> <pre class="prettyprint"><code>try: with exception_guard(ZeroDivisionError): 1/0 # raises ZeroDivisionError except RuntimeError: print ('ZeroDivisionError replaced by RuntimeError') @exception_guard(KeyError) def demo(): return {}['key'] # raises KeyError try: demo() except RuntimeError: print ('KeyError replaced by RuntimeError') </code></pre> Retry Decorator in Python (Python) 2017-01-11T10:10:30-08:00Alfehttp://code.activestate.com/recipes/users/4182236/http://code.activestate.com/recipes/580745-retry-decorator-in-python/ <p style="color: grey"> Python recipe 580745 by <a href="/recipes/users/4182236/">Alfe</a> (<a href="/recipes/tags/aspect/">aspect</a>, <a href="/recipes/tags/except/">except</a>, <a href="/recipes/tags/exception/">exception</a>, <a href="/recipes/tags/retry/">retry</a>, <a href="/recipes/tags/try/">try</a>). </p> <p>This is a Python decorator which helps implementing an aspect oriented implementation of a <em>retrying</em> of certain steps which might fail sometimes. A typical example for this would be communication processes with the outside world, e. g. HTTP requests, allocation of some resource, etc. To use it, refactor the step in question into a (local) function and decorate this with the <code>retry</code> decorator. See examples in the discussion sector below.</p> Trap KeyboardInterrupt and EOFError for graceful program termination (Python) 2016-11-13T20:17:03-08:00Vasudev Ramhttp://code.activestate.com/recipes/users/4173351/http://code.activestate.com/recipes/580718-trap-keyboardinterrupt-and-eoferror-for-graceful-p/ <p style="color: grey"> Python recipe 580718 by <a href="/recipes/users/4173351/">Vasudev Ram</a> (<a href="/recipes/tags/ascii/">ascii</a>, <a href="/recipes/tags/error/">error</a>, <a href="/recipes/tags/exception/">exception</a>, <a href="/recipes/tags/handler/">handler</a>, <a href="/recipes/tags/shutdown/">shutdown</a>, <a href="/recipes/tags/terminate/">terminate</a>, <a href="/recipes/tags/utilities/">utilities</a>, <a href="/recipes/tags/utility/">utility</a>). </p> <p>This recipe shows how to trap the KeyboardInterrupt and EOFError Python exceptions so that they do not crash your program. As a vehicle to show this, it uses a small Python utility that shows the ASCII code for any ASCII character you type.</p> RecursionError exception: concise and informative output (Python) 2015-07-05T23:46:59-07:00elazarhttp://code.activestate.com/recipes/users/4187847/http://code.activestate.com/recipes/578660-recursionerror-exception-concise-and-informative-o/ <p style="color: grey"> Python recipe 578660 by <a href="/recipes/users/4187847/">elazar</a> (<a href="/recipes/tags/debugging/">debugging</a>, <a href="/recipes/tags/exception/">exception</a>, <a href="/recipes/tags/handler/">handler</a>, <a href="/recipes/tags/recursion/">recursion</a>). Revision 3. </p> <p>Replaces the default exception hook with one that, upon "infinite recursion", removes the last cycle. This results in a significantly cleaner and shorter error message.</p> <p>Usage: simply import &lt;module&gt; as _</p> <p>For more details see the descussion here: <a href="https://mail.python.org/pipermail/python-ideas/2013-September/023190.html" rel="nofollow">https://mail.python.org/pipermail/python-ideas/2013-September/023190.html</a></p> Retry loop (Python) 2013-05-23T20:45:01-07:00Ryan Nowakowskihttp://code.activestate.com/recipes/users/4186624/http://code.activestate.com/recipes/578527-retry-loop/ <p style="color: grey"> Python recipe 578527 by <a href="/recipes/users/4186624/">Ryan Nowakowski</a> (<a href="/recipes/tags/exception/">exception</a>, <a href="/recipes/tags/generator/">generator</a>, <a href="/recipes/tags/loop/">loop</a>, <a href="/recipes/tags/retry/">retry</a>, <a href="/recipes/tags/timeout/">timeout</a>). </p> <p>Encapsulates the logic of a retry loop using a generator function.</p> Python Exception Chains (or Trees) (Python) 2013-02-04T15:15:22-08:00Alfehttp://code.activestate.com/recipes/users/4182236/http://code.activestate.com/recipes/578252-python-exception-chains-or-trees/ <p style="color: grey"> Python recipe 578252 by <a href="/recipes/users/4182236/">Alfe</a> (<a href="/recipes/tags/cause/">cause</a>, <a href="/recipes/tags/chain/">chain</a>, <a href="/recipes/tags/exception/">exception</a>, <a href="/recipes/tags/python/">python</a>, <a href="/recipes/tags/reason/">reason</a>, <a href="/recipes/tags/reraise/">reraise</a>, <a href="/recipes/tags/tree/">tree</a>). Revision 2. </p> <p>I have here an approach for chaining exceptions in case a lower layer (<em>library</em>) raises an exception which is caught in an upper layer (<em>application</em>) and later given as <em>cause</em> when a different exception is raised. Passing this <em>cause</em> exception is meant to offer access to the stack trace of the inner exception for debugging.</p> <p>This approach is implemented in Python 3 and in Java, so it definitely makes sense; you also quickly find questions on <a href="http://stackoverflow.com">Stackoverflow</a> concerning it.</p> <p>I even extended this feature by not only using chains of exceptions but also trees. Trees, why trees? Because I had situations in which my application layer tried various approaches using the library layer. If all failed (raised an exception), my application layer also raised an exception; this is the case in which I wanted to pass more than one cause exception into my own exception (hence the tree of causes).</p> <p>My approach uses a special Exception class from which all my exceptions will inherit; standard exception must be wrapped (directly after catching, to preserve the exception stack trace). Please see the examples contained in the code below. The exception itself is rather small.</p> <p>I'd be happy to hear any comments regarding memory leaks (I didn't find any but one never knows), usability, enhancements or similar.</p> Retry loop (Python) 2013-05-24T05:19:50-07:00Oren Tiroshhttp://code.activestate.com/recipes/users/2033964/http://code.activestate.com/recipes/578163-retry-loop/ <p style="color: grey"> Python recipe 578163 by <a href="/recipes/users/2033964/">Oren Tirosh</a> (<a href="/recipes/tags/exception/">exception</a>, <a href="/recipes/tags/generator/">generator</a>, <a href="/recipes/tags/loop/">loop</a>, <a href="/recipes/tags/retry/">retry</a>, <a href="/recipes/tags/timeout/">timeout</a>). Revision 4. </p> <p>Encapsulates the logic of a retry loop using a generator function.</p> Context manager to prevent calling code from catching exceptions (Python) 2012-06-17T09:20:56-07:00Oren Tiroshhttp://code.activestate.com/recipes/users/2033964/http://code.activestate.com/recipes/577863-context-manager-to-prevent-calling-code-from-catch/ <p style="color: grey"> Python recipe 577863 by <a href="/recipes/users/2033964/">Oren Tirosh</a> (<a href="/recipes/tags/context_manager/">context_manager</a>, <a href="/recipes/tags/exception/">exception</a>). </p> <p>The following context manager causes any exceptions raised inside it to print a stack trace and exit immediately. The calling scope is not given a chance to catch the exception.</p> Abstract method decorator (Python) 2011-04-20T21:50:23-07:00jimmy2timeshttp://code.activestate.com/recipes/users/4177690/http://code.activestate.com/recipes/577666-abstract-method-decorator/ <p style="color: grey"> Python recipe 577666 by <a href="/recipes/users/4177690/">jimmy2times</a> (<a href="/recipes/tags/abstract/">abstract</a>, <a href="/recipes/tags/decorator/">decorator</a>, <a href="/recipes/tags/exception/">exception</a>, <a href="/recipes/tags/inheritance/">inheritance</a>, <a href="/recipes/tags/method/">method</a>, <a href="/recipes/tags/python/">python</a>, <a href="/recipes/tags/subclass/">subclass</a>). Revision 5. </p> <p>A simple decorator that helps define abstract methods: when such a method is called, an appropriate exception is raised.</p> Easy Exception, Error Handling and Debugging with Auto Logging (Python) 2010-04-06T20:40:05-07:00AJ. Mayorgahttp://code.activestate.com/recipes/users/4173476/http://code.activestate.com/recipes/577144-easy-exception-error-handling-and-debugging-with-a/ <p style="color: grey"> Python recipe 577144 by <a href="/recipes/users/4173476/">AJ. Mayorga</a> (<a href="/recipes/tags/debug/">debug</a>, <a href="/recipes/tags/debugging/">debugging</a>, <a href="/recipes/tags/error_propagation/">error_propagation</a>, <a href="/recipes/tags/exception/">exception</a>, <a href="/recipes/tags/logging/">logging</a>). Revision 5. </p> <p>Being new to Python and trying to chase where in my project exceptions were taking place always seems to take up a large amount of time. So I created this class that I now pretty use in all my projects to help me save time tracking exceptions and errors. its also has the ability to generate error logs or to output SQL query and data tuples for Database logging. Ive added sample code to give you an idea of how I normally use it. Hope this helps its saved me hours in tracking error/exception. Feed back would be great, mind you havent been Python all that long</p> Exception handling in a single line (Python) 2009-10-09T01:07:52-07:00Radek Szklarczykhttp://code.activestate.com/recipes/users/2847011/http://code.activestate.com/recipes/576872-exception-handling-in-a-single-line/ <p style="color: grey"> Python recipe 576872 by <a href="/recipes/users/2847011/">Radek Szklarczyk</a> (<a href="/recipes/tags/exception/">exception</a>, <a href="/recipes/tags/expression/">expression</a>, <a href="/recipes/tags/function/">function</a>, <a href="/recipes/tags/list_comprehension/">list_comprehension</a>, <a href="/recipes/tags/wrapper/">wrapper</a>). Revision 16. </p> <p>The rules of <em>duck typing</em> in python encourage programmers to use the "try...except..." clause. At the same time python with new versions enables to use more powerful list comprehensions (for example Conditional Expressions). However, it is impossible to write the "try...except..." clause in a list comprehension. The following recipe "protects" a function against exception and returns a default value in the case when exception is thrown.</p> self-logging exceptions (Python) 2009-05-27T17:43:56-07:00geremy condrahttp://code.activestate.com/recipes/users/4170000/http://code.activestate.com/recipes/576781-self-logging-exceptions/ <p style="color: grey"> Python recipe 576781 by <a href="/recipes/users/4170000/">geremy condra</a> (<a href="/recipes/tags/exception/">exception</a>, <a href="/recipes/tags/logging/">logging</a>). Revision 3. </p> <p>Pretty frequently I find myself needing to log my exceptions, and rather than produce a tangled mess of boilerplate code, I went ahead and put together this snippet to act as a base class for all those exceptions.</p>