A file reading-writing exception handling by adding a log record to a file
I'd like to write a log record in case of a failed attempt of a file reading(writing) operation, something like:
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.AppendA开发者_如何转开发llText(recfilepath, rectoadd);
}
Is this a correct way of doing that? What if in the above example the attempt of writing a log record (File.AppendAllText(recfilepath, rectoadd);
) fail as well?
Never catch Exception type - by this way you hide program bugs. Catch only expected exception types - in this case, it can be IOException.
Inside catch block, you can add another try-catch block, and report logging error by some another way: Trace, message box etc.
Assuming that a failure is exceptional, then using an exception like this is fine.
If you are concerned that the writing may fail, then encapsulate this in a function. catch and failures here and record both messages some other way. You can repeat this as long as you feel it is necessary. However, at some point you have to accept that the system is broken and you cannot record the error. You will probably know this anyway by the smoke rising from the server.
I reckon there is a limit to what one can handle. If you reach a point where you cannot handle an exception either ignore it or have your system fail outright.
This really a bad situation for you :-) There are two things you could try:
- Put File.AppendAllText(recfilepath, rectoadd); inside another try-catch block and in the catch block, just write to a log console the exception.
- Use log4net or implement a log class yourself and make sure the log writer never throw exception.
File.AppendAllText
- 9 possible exceptions (according to msdn, link is here)
EventLog
(msdn link) on the otherhand allows you to write exceptions to Windows Event Log. And EventLog.WriteEntry
has only 3 possible exceptions (EventLog.WriteEntry exceptions). switching to EventLog.WriteEntry
method will reduce the number of possible exceptions. But... if you still want to try and log exceptions to some specific file, leave ur current logic. just add another try catch block i.e.
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
}
}
精彩评论