2016-05-17 90 views
0

我有過這樣的循環運行一個python腳本硒...Python的硒錯誤處理

for i, refcode in enumerate(refcode_list): 

    try: 
     source_checkrefcode() 
    except TimeoutException: 
     pass 
     csvWriter.writerow([refcode, 'error', timestamp]) 

如果在source_checkrefcode過程中出現問題,則腳本錯誤崩潰。

如何將錯誤處理添加到此循環,以便它只是移動到下一個項目而不是崩潰?

回答

5

您可以添加對異常消息的檢查,下面是您理解的示例代碼。

for i, refcode in enumerate(refcode_list): 
    try: 
     source_checkrefcode() 
    except Exception as e: 
     if 'particular message' in str(e): 
      # Do the following 
      # if you don't want to stop for loop then just continue 
      continue 
+0

我原來的代碼看起來出來TimeoutException異常,但您的示例使用異常。這個新的代碼是否還會捕獲TimeoutException? – fightstarr20

+0

是的,其實異常會捕獲所有類型的異常。然後你可以在它的字符串消息上添加一個檢查。例如。如果str(e)中的'TimeountException':在str(e)中執行此elif'Another Exception':執行此操作等等 –

0

我同意哈桑的答案。但是如果你使用continue,那麼你將不會處理任何其他的代碼塊。

for i, refcode in enumerate(refcode_list): 
    try: 
     source_checkrefcode() 
    except Exception as e: 
     if 'particular message' in str(e): 
      # Do the following 
      # if you don't want to stop for loop then just continue 
      continue 
    # another code of block will skip. Use pass or continue as per your requirement. 

你必須瞭解通之間的區別,並繼續 Link