繁体   English   中英

我可以通过在“__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)

如此所述,您可以创建异常处理程序和猴子补丁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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM