假设我们有这个简单的主程序:
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')
正在运行的应用程序非常复杂,并且正在创建多个窗口。为每个内部工作的类做一个异常处理程序是相当繁琐的,所以我在想是否有办法捕获在main中执行app
期间引发的任何异常,并在终止程序之前执行某些操作。
有没有办法实现这个目标?
您可以创建自己的错误处理程序,以捕获标准错误。比如这样;
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_()