0

I've read here here and other places that, as a rule of thumb asyncio.CancelledError should be reraised. Is this simply to avoid problems shutdown down, or are there other reasons?

Suppose I wanted to raise an exception when a worker monitoring a long test is canceled. I want to raise an exception only at the end of the test, at shutdown). Is it generally safe to catch CancelledError and re-raise a different exception?

@astask
async def monitor():
   ex = None
   try:
      while True:
          ex_ = await check()
          if ex is None and ex_ is not None:
             ex = ex_
             logger.error("Failed. Let's see it fails more...")

   except:
     if ex: raise ex
     raise

   
@astask
async def test():
  ... run the test

async def test():
   tasks = [monitor(), test()]
   await awaitFirstTaskDoneThaenCancelAllThenRaiseFirstTaskException(tasks)
user48956
  • 14,850
  • 19
  • 93
  • 154
  • For what I understand it's mainly for propagating Cancellation to allow other tasks to gracefully stop in case of an 'ungraceful event', and therefore it is not mandatory if one knows what they are doing. Since that what you're trying to do is kinda similar to what [`asyncio.gather`](https://docs.python.org/3/library/asyncio-task.html#asyncio.gather) and [`trio`](https://trio.readthedocs.io/en/stable/reference-core.html#errors-in-multiple-child-tasks) already does - former preventing child cancellation propagating, latter saving and re-raising later - I find your idea totally justifiable. – jupiterbjy Oct 12 '22 at 06:19

0 Answers0