pythonexceptionpyqt4application-restart

How to restart PyQt application after exception is raised


I built some error dialogs within exceptions in my code. Everything works, except that the program continues executing the code after the exception. So I built in sys.exit():

try:
    hdf = pd.HDFStore(filepath_hdf)
except:
    QMessageBox.about(self, 'Error!','Filepath can't be read')
    sys.exit()

Unfortunately this shuts down the whole application. How do I "restart" the application, when an exception is raised? By that, I mean how to return to the starting point of the application?


Solution

  • That is what the else clause of a try/except statement is for:

    try:
        hdf = pd.HDFStore(filepath_hdf)
    except:
        QMessageBox.warning(self, 'Error', 'Filepath cannot be read')
    else:
        # do normal stuff here...
    

    There should be no need to restart the whole application if an error occurs, unless the error is truly fatal (which would mean it was literally impossible to continue running, and thus require an immediate shutdown). The whole point of exception handling is to be able to recover gracefully from non-fatal errors.

    There is no general way to return an application to its starting state. Every application is different, so you will need to write your own "reset" method that clears the current state and reinitializes certain gui elements wherever appropriate. This "reset" method will very likely look a lot like some of the setup/init code you are already using. So it should just be matter a refactoring that code into a separate method that will be called when the application starts up, and then whenever a reset is required.