2017-02-14 99 views
-2

我遇到了try-except方法的問題,我想通過將這些錯誤發送到我的郵件來監視腳本中的任何錯誤,該腳本只檢查文件存在,它看起來像:在Python中嘗試除外法錯誤

def check_file_existence(): 
    try: 
     with open('\\\\ntsrv1\\tohna\\SecurityTeam\\Varonis\\Varonis_monitoring_report\\Varonis_Action_Report.csv', 'r') as temp_file: 
      temp_file.close() 
    except ValueError as e: 
     e = str(e) 
     print(e) 
     status_mail_notofication('error in move_report_to_folder_adding_date_to_file Function under varonis_report_analysis script ','there was an error in check_file_existence Function','[email protected]') 
     sys.exit(0) 
    return 

運行與目的的代碼來得到一個錯誤

後,我得到這個:

IO錯誤:[錯誤2]沒有這樣的文件或目錄:「\\ ntsrv1 \ tohna \ SecurityTeam \ Varonis \ Varonis_monitoring_report \ Varonis_Action_Report.csv'

,它並沒有去除了一部分,我需要得到郵件與錯誤,它只是停止

人知道爲什麼嗎?

TNX

+2

爲什麼'ValueError'會捕獲IOError?你選擇性地試圖處理前者,而後者應該提出異議。 – roganjosh

回答

0

也許使用except IOError as e:或只需except:以確保它捕獲錯誤

+0

作品完美! TNX – shamirs888

0
except ValueError as e: 
    print("ValueError caught: " + str(e)) 

只是抓住ValueError類型的異常。例外傾向於從Exception類派生的,所以這會趕上任何正常例外:

except Exception as e: 
    print("Exception caught:" + str(e)) 

是完全確定你捕捉一切,你可以使用:

except: 
    print("Unknown exception caught")