Python exception groups
Python exception groups
Posted Mar 11, 2021 22:53 UTC (Thu) by NYKevin (subscriber, #129325)In reply to: Python exception groups by LtWorf
Parent article: Python exception groups
Yes, no, sort of. It's complicated.
Yes: You can raise a tree of exceptions by raising something like ExceptionGroup([FooError(), ExceptionGroup([BarError(), ...]), ...]) and so on, and the same error can appear in multiple different branches, or even multiple times in the same branch. All of those exceptions will preserve their original tracebacks and other contextual information. PEP 654 explicitly calls that out as a supported use case, and makes cogent arguments for why it should be supported. Don't expect this to go away unless the proposal gets axed altogether.
No/sort of: If someone writes, say, except *(FooError, BarError) as err, then they will get an ExceptionGroup which has been filtered to contain all instances of FooError and BarError, preserving the original tree structure, but with non-matching exceptions (and the resulting empty branches) deleted. They are then expected to consume that tree by hand; if you want to handle each exception individually, you need to write the tree traversal code yourself, or use .subgroup() on a callback function with side effects, which is honestly kind of horrifying.
The expectation, so far as I can tell, is that this will be used for top-level "can't do any meaningful recovery" situations, where you're basically just going to log it, maybe do some minimal cleanup, and then return to the main event loop (or whatever you have instead of a "main event loop"). If you actually want to take these things apart and do nontrivial recovery, then the PEP assumes you will catch those errors before they get coalesced into groups in the first place (for example, if you're throwing a group out of asyncio.gather(), then the individual coroutines should handle recoverable errors themselves, so that asyncio.gather() never even sees them).
See also: https://github.com/python/exceptiongroups/issues/3#issuec...