[英]A file reading-writing exception handling by adding a log record to a file
如果文件讀取(寫入)操作嘗試失敗,我想寫一條日志記錄,例如:
try
{
//some file operation, for example:
TextReader tr2 = new StreamReader(nfilepath);
resultN = tr2.ReadLine();
tr2.Close();
}
catch (Exception ex)
{
string recfilepath = "...
string rectoadd = "RecDateTime=" + DateTime.Now.ToString()+ ...+ex.Message.ToString();
File.AppendAllText(recfilepath, rectoadd);
}
這是這樣做的正確方法嗎? 如果在上面的示例中寫入日志記錄( File.AppendAllText(recfilepath, rectoadd);
)的嘗試也失敗了怎么辦?
永遠不要捕獲異常類型 - 通過這種方式您可以隱藏程序錯誤。 只捕獲預期的異常類型——在這種情況下,它可以是 IOException。
在 catch 塊中,您可以添加另一個 try-catch 塊,並通過其他方式報告日志記錄錯誤:跟蹤、消息框等。
假設失敗是異常的,那么使用這樣的異常就可以了。
如果您擔心寫入可能會失敗,請將其封裝在 function 中。 在這里捕獲和失敗,並以其他方式記錄這兩條消息。 只要您認為有必要,您就可以重復此操作。 但是,在某些時候,您必須接受系統已損壞並且您無法記錄錯誤。 無論如何,您可能會通過服務器升起的煙霧知道這一點。
我認為一個人可以處理的事情是有限的。 如果您達到無法處理異常的程度,請忽略它或讓您的系統徹底失敗。
這對你來說真的很糟糕:-)你可以嘗試兩件事:
File.AppendAllText
- 9 個可能的異常(根據 msdn,鏈接在這里)
另一方面, EventLog
( msdn 鏈接)允許您將異常寫入 Windows 事件日志。 而EventLog.WriteEntry
只有 3 個可能的異常( EventLog.WriteEntry 異常)。 切換到EventLog.WriteEntry
方法將減少可能的異常數量。 但是...如果您仍想嘗試將異常記錄到某個特定文件,請保留您當前的邏輯。 只需添加另一個 try catch 塊,即
catch (Exception ex)
{
try
{
string recfilepath = "...
string rectoadd = "RecDateTime=" + DateTime.Now.ToString()+ ...+ex.Message.ToString();
File.AppendAllText(recfilepath, rectoadd);
}
catch ()
{
// do Event logging
//also moving the string rectoadd declaration outside the try catch scope
// will give u ability to use it in this catch block to write it to the windows event log
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.