如果我在“ 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)
uj5u.com熱心網友回復:
正如這里所解釋的,您可以創建一個例外處理程式和猴子補丁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
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/437707.html
上一篇:shaded.databricks.org.apache.hadoop.fs.azure.AzureException:掛載后嘗試列出目錄時出現例外
