Error handling in context managers

Marko Rauhamaa marko at pacujo.net
Mon Jan 16 14:29:42 EST 2017


Steve D'Aprano <steve+python at pearwood.info>:

> or you can let the context manager do what it does, and write your own code
> to do what you do:
>
> try:
>     with ...:
>        ...
> except:
>     ...

Even better:

    try:
       a = open(...)
    except ...:
       ...
    with a:
       ...

You want to catch exceptions immediately after (potentially) raising
them.


Marko


More information about the Python-list mailing list