[Python-ideas] Block-Scoped Exception Handlers

Nick Coghlan ncoghlan at gmail.com
Wed May 4 20:41:53 EDT 2016

On 5 May 2016 9:16 am, "Kyle Lahnakoski" <klahnakoski at mozilla.com> wrote:
> On 5/4/2016 7:05 PM, cs at zip.com.au wrote:
> > I also like context from close to where the exception occurred, while
> > doing that catching at whatever the suitable outer layer may be, as
> > normal. Let me show you what I do...
> >
> > I have a module "cs.logutils":
> >
> I really like the idea of using a `with` clause for simplify exception
> chaining.  I am concerned I would be missing some of the locals
> available at exception time, which the `with` clause would not have
> access to, but more introspection may solve that too.  It does not solve
> the indent problem, but I could live with that if it made the code
> simpler in other ways.
> Many of my exception handlers are multiline, and I do not think the
> `with` clause strategy would work there.

In combination with contextlib.contextmanager (and perhaps passing in
references to relevant locals), with statements are designed to handle
factoring out almost arbitrary exception handling. Chaining a consistent
error, for example:

def chain_errors(exc_to_raise):
    except Exception as e:
        raise exc_to_raise from e

This is most useful for supplying state that's useful for debugging
purposes (e.g. the codec infrastructure tries to do something like that in
order to report the codec name)


> _______________________________________________
> Python-ideas mailing list
> Python-ideas at python.org
> https://mail.python.org/mailman/listinfo/python-ideas
> Code of Conduct: http://python.org/psf/codeofconduct/
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20160505/5696f22c/attachment.html>

More information about the Python-ideas mailing list