我可以通过在“__main__”中使用 try 和 catch 来捕获所有异常吗
Can I catch all exceptions by using try and catch in "__main__"
如果我在“main”中使用 try except 块,是否也可以捕获所有异常?我试着捕捉异常,但我做不到。我附上了异常图像和代码
enter code here
if __name__ == '__main__':
try:
app = QtWidgets.QApplication(sys.argv)
window = MainWindow()
debug_file = "errors.txt"
window.setWindowFlags(QtCore.Qt.WindowType.CustomizeWindowHint)
window.show()
ret = app.exec_()
[enter image description here][1]sys.exit()
except KeyboardInterrupt:
print("Theres an exception")
traceback_str = "".join(traceback.format_exc())
with open("errors.txt", "a") as log:
log.write(datetime.now().isoformat() + "\n")
log.write(traceback_str + "\n")
print(traceback_str)
except AttributeError:
print("Theres an exception")
traceback_str ="".join(traceback.format_exc())
with open("errors.txt","a") as log:
log.write(datetime.now().isoformat()+"\n")
log.write(traceback_str +"\n")
print(traceback_str)
如 here 所述,您可以创建异常处理程序和猴子补丁 sys.excepthook
:
import sys
import logging
logger = logging.getLogger(__name__)
def handle_unhandled_exception(e_type, e_value, e_traceback):
logger.critical("Unhandled exception", exc_info=(e_type, e_value, e_traceback))
do_other_stuff_at_your_convenience()
sys.excepthook = handle_unhandled_exception
如果我在“main”中使用 try except 块,是否也可以捕获所有异常?我试着捕捉异常,但我做不到。我附上了异常图像和代码
enter code here
if __name__ == '__main__':
try:
app = QtWidgets.QApplication(sys.argv)
window = MainWindow()
debug_file = "errors.txt"
window.setWindowFlags(QtCore.Qt.WindowType.CustomizeWindowHint)
window.show()
ret = app.exec_()
[enter image description here][1]sys.exit()
except KeyboardInterrupt:
print("Theres an exception")
traceback_str = "".join(traceback.format_exc())
with open("errors.txt", "a") as log:
log.write(datetime.now().isoformat() + "\n")
log.write(traceback_str + "\n")
print(traceback_str)
except AttributeError:
print("Theres an exception")
traceback_str ="".join(traceback.format_exc())
with open("errors.txt","a") as log:
log.write(datetime.now().isoformat()+"\n")
log.write(traceback_str +"\n")
print(traceback_str)
如 here 所述,您可以创建异常处理程序和猴子补丁 sys.excepthook
:
import sys
import logging
logger = logging.getLogger(__name__)
def handle_unhandled_exception(e_type, e_value, e_traceback):
logger.critical("Unhandled exception", exc_info=(e_type, e_value, e_traceback))
do_other_stuff_at_your_convenience()
sys.excepthook = handle_unhandled_exception