您好,我有一個函數可以解析文件中的前 60 行,并且應該在存在完全空白的行時提醒用戶。然而,這些可能發生在這 60 行中的任何位置,因此我希望腳本解析整個 60 行,主要是因為我需要其中幾行的數據來進行錯誤報告。我們可能想知道這些錯誤將來會發生在哪里。我寫了這個:def header_data(data): dictionary = {} datalen = len(data) itrcntr = 0 try: for line in data: itrcntr += 1 if line.isspace(): raise Exception('File has badly formatted header data line(s)') else: linesplit = line.rstrip().split(":") if len(linesplit) > 1: dictionary[linesplit[0]] = linesplit[1].strip() return dictionary except Exception as e: errmsg = str(e) if itrcntr == datalen: return (dictionary, errmsg) else: pass 有了這個函數,我希望如果它發現 itrcntr 不等于 datalen,它會通過并返回到 try 塊并繼續到下一行。但這并沒有發生。相反,它會跳出函數并在函數調用者的下一行中繼續。如何讓它繼續循環,直到到達循環末尾,然后返回字典以及錯誤消息?或者這不能通過 try catch 異常處理程序來完成嗎?
2 回答

慕田峪9158850
TA貢獻1794條經驗 獲得超7個贊
除非你想捕獲除 的情況以外的異常,否則line.isspace我根本不會使用塊。try只需將您的錯誤收集在列表中,例如:
errors = []
for line in data:
itrcntr += 1
if line.isspace():
errors.append('File has badly formatted header data at line %d.' % itrcntr)
# then at the end:
if errors:
# do something about it...

慕妹3146593
TA貢獻1820條經驗 獲得超9個贊
如果發生任何異常,try 子句將被跳過,而 except 子句將運行。
如果您在 Try 中的任何位置引發異常,則其他所有內容都將被跳過。因此,如果您希望循環繼續,那么就不要使用 Try except。
只需收集所有錯誤消息然后將其返回即可。
添加回答
舉報
0/150
提交
取消