0

I would like to handle the exception raised in a thread in the function in which it was started.

def thread_fn():
  while True:
    ...
    raise Exception('Exception occurred !!!!')

def main():
  t = threading.Thread(target=thread_fn)
  t.start()

  try:
    ...
    ...
  except Exception as e:
    print(e.message)
    # Expecting the exception raised by thread_fn

As above code states, the exception raised by thread_fn should be caught in main.

Shiva
  • 81
  • 2
  • 10
  • Are you actually doing anything with ``t`` inside the ``try`` block? What do you expect to happen when ``main`` has already proceeded past the ``try``, and ``thread_fn`` fails afterwards? – MisterMiyagi Dec 03 '20 at 16:08
  • there will be sequence of statements in try block. I'm expecting thread_fn to be stopped after try block – Shiva Dec 03 '20 at 16:23
  • So why use a `Thread`? Why no just call `thread_fn()` from inside the `try:` block? – quamrana Dec 03 '20 at 16:35
  • That's not possible. You use messaging through a queue https://stackoverflow.com/questions/2829329/catch-a-threads-exception-in-the-caller-thread-in-python – Mace Dec 03 '20 at 16:55

0 Answers0