Melon
Melon

Reputation: 614

Catching exception from timer

I am trying to create a watchdog class, that will throw an exception after specified time:

from threading import Timer
from time import sleep

class watchdog():
  def _timeout(self):
    #raise self
    raise TypeError

  def __init__(self):
    self.t = Timer(1, self._timeout)

  def start(self):
    self.t.start()

try:
  w = watchdog()
  w.start()
  sleep(2)
except TypeError, e:
  print "Exception caught"
else:
  print "Of course I didn't catch the exception"

This exception is not caught, as the exception is thrown from completely different context, hence we will see the last message.

My question is, how can I modify the code, so the exception will be caught?

Upvotes: 5

Views: 3947

Answers (1)

Elazar
Elazar

Reputation: 21595

This is not possible, as you suggested, and there is no api for abruptly stopping a thread, either, which rules out other potential solutions.

I believe your best solution is to let the watchdog set a flag, and let the test read it at certain points. Similarly, your test can simply check the duration from time to time.

Note that if the "flag" would set in a way that will cause the main thread to raise an exception (for example, deleting attributes from objects), it'll be just as effective.

The other possibility is to use multiprocessing instead of multythreading, if it is possible for your application.

Upvotes: 3

Related Questions