Issue
Suppose we have this simple main program:
from matplotlib.backends.qt_compat import QtWidgets
from initial import InitialWindow
if __name__ == '__main__':
try:
app = QtWidgets.QApplication([])
ex = InitialWindow()
ex.show()
app.exec_()
except:
# Do something
print('Hello')
The application being run is pretty complex, and there are several windows being created. Doing an exception handler for each class that is working internally is rather tedious, so I was thinking if there is a way to catch any exception raised during the execution of app
in the main, and do something before terminating the program.
Is there a way to achieve this?
Solution
You can create your own error handler which will capture standard error. For example like this;
import sys
import traceback
from matplotlib.backends.qt_compat import QtWidgets
from initial import InitialWindow
def error_handler(etype, value, tb):
error_msg = ''.join(traceback.format_exception(etype, value, tb))
# do something with the error message, for example print it
if __name__ == '__main__':
sys.excepthook = error_handler # redirect std error
app = QtWidgets.QApplication([])
ex = InitialWindow()
ex.show()
app.exec_()
Answered By - ruohola
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.