Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python, how to keep program going after exception is caught

probably a simple question as I fairly new to python and programming in general but I am currently working on improving a program of mine and can't figure out how to keep the program going if an exception is caught. Maybe I am looking at it the wrong way but for example I have something along these lines:

    self.thread = threading.Thread(target=self.run)
    self.thread.setDaemon(True)
    self.thread.start()

    def run(self):
        logging.info("Starting Awesome Program") 
        try:
            while 1:
                awesome_program(self)
    except:
        logging.exception('Got exception on main handler')
        OnError(self)

    def OnError(self):
        self.Destroy()

Obviously I am currently just killing the program when an error is reached. awesome_program is basically using pyodbc to connect and run queries on a remote database. The problem arises when connection is lost. If I don't catch the exceptions the program just freezes so I set it up as it is above which kills the program but this is not always ideal if no one is around to manually restart it. Is there an easy way to either keep the program running or restert it. Feel free to berate me for incorrect syntax or poor programming skills. I am trying to teach myself and am still very much a novice and there is plenty I don't understand or am probably not doing correctly. I can post more of the code if needed. I wasn't sure how much to post without being overwhelming.

like image 478
ouldsmobile Avatar asked Sep 15 '25 00:09

ouldsmobile


2 Answers

Catch the exception within the loop, and continue, even if an exception is caught.

def run(self):
        logging.info("Starting Awesome Program") 
        while 1:
            try:
                awesome_program(self)
            except:
                logging.exception('Got exception on main handler')
                OnError(self)

BTW:

  • Your indentation seems messed up.
  • I'd prefer while True. Python has bool type, unlike C, so when a bool is expected - give while a bool.
like image 108
Thorsten Kranz Avatar answered Sep 17 '25 14:09

Thorsten Kranz


You're looking for this:

def run(self):
     while True:
         try:
             do_things()
         except Exception as ex:
             logging.info("Caught exception {}".format(ex))
like image 27
asthasr Avatar answered Sep 17 '25 14:09

asthasr