[英]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.