[Answer]-How to run again same method of class in case of Exception

1👍

You can enclose the try except block inside a while True loop and break when you want.

Similar question was answered here: How to retry after exception in python?

0👍

I’d prefer a constant number of trials instead of a while True loop because you can find yourself in an infinite loop if the Queue.Empty error persists. It would also be nice to separate the queue.get() part (where you expect the error) from the possibly long entry processing part. I recommend reorganizing your code like this:

 def getEntry(self,trials=1):
    for i in range(trials):
        try:
           return self.import_queue.get()

        except Queue.Empty:
           continue   # move to next trial 

    raise Queue.Empty   # raise error if not returned after given number of trials 


 def run(self):
     entry = self.getEntry(trials=2)
     do_something_with_entry()

UPDATE

To fire as long as queue is not empty, you can call run() in a while loop and break on error:

 def runUntilNotEmpty(self):
     while True:
           try:
                self.run()
           except Queue.Empty:
                break

Breaking a while True loop on error is much better than breaking on success, because
1) You will definitely not run into an infinite loop, because you cannot have an infinite queue.
2) You don’t just vanish your error, but you can manage it somehow (raise warnings etc.).

Leave a comment