[Python-Dev] Why not using "except: (...) raise" to cleanup on error?

Guido van Rossum guido at python.org
Mon Jun 4 12:45:46 EDT 2018


It is currently a general convention in asyncio to only catch Exception,
not BaseException. I consider this a flaw and we should fix it, but it's
unfortunately not so easy -- the tests will fail if you replace all
occurrences of Exception with BaseException, and it is not always clear
what's the right thing to do. E.g. catching KeyboardInterrupt may actually
make it harder to stop a runaway asyncio app.

We should move this discussion to the issue tracker.

On Mon, Jun 4, 2018 at 9:11 AM, Victor Stinner <vstinner at redhat.com> wrote:

> Hi,
>
> I just read a recent bugfix in asyncio:
>
> https://github.com/python/cpython/commit/9602643120a509858d0bee4215d7f1
> 50e6125468
>
> + try:
> +     await waiter
> + except Exception:
> +     transport.close()
> +     raise
>
> Why only catching "except Exception:"? Why not also catching
> KeyboardInterrupt or MemoryError? Is it a special rule for asyncio, or
> a general policy in Python stdlib?
>
> For me, it's fine to catch any exception using "except:" if the block
> contains "raise", typical pattern to cleanup a resource in case of
> error. Otherwise, there is a risk of leaking open file or not flushing
> data on disk, for example.
>
> Victor
> _______________________________________________
> Python-Dev mailing list
> Python-Dev at python.org
> https://mail.python.org/mailman/listinfo/python-dev
> Unsubscribe: https://mail.python.org/mailman/options/python-dev/
> guido%40python.org
>



-- 
--Guido van Rossum (python.org/~guido)
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-dev/attachments/20180604/01e99995/attachment.html>


More information about the Python-Dev mailing list