Reputation: 81
I'm writing a mobile application that will actually be running as a Task in ArcGIS, but my question is basically C# error handling. I'm using a while
loop to loop through records and using StreamWriter
to log a failed attempt to read the data. I've broken each field into its own seperate try
catch
so that I can write which record and which field caused the failure to the log file. Example below.
try
{
TrafficLanesCount = Convert.ToByte(ModifiedFDR.GetValue(ModifiedFDR.GetOrdinal("TRAFICLN")));
}
catch
{
sw.WriteLine(DOTNumber + " " + "TrafficLanesCount");
}
I'm saving at the end of the while loop, but if anything fails, I want to log it, skip that record, and continue on with the next record. Does anyone know a way to do this?
Upvotes: 1
Views: 702
Reputation: 1067
Using the code provided, I would go with something like this:
var errorList = new List<Exception>();
foreach(var record in records)
{
try
{
try
{
TrafficLanesCount = Convert.ToByte(ModifiedFDR.GetValue(ModifiedFDR.GetOrdinal("TRAFICLN")));
}
catch
{
throw new Exception(new string(DOTNumber + " " + "TrafficLanesCount"));
}
}
catch (Exception exp)
{
errorList.Add(exp);
}
}
And afterwords, you can loop through the exceptions in the list and handle them at that point.
Upvotes: 0
Reputation: 9669
Instead of
sw.WriteLine(DOTNumber + " " + "TrafficLanesCount");
You could use
File.AppendAllText("path/to/log.txt", DOTNumber + " " + "TrafficLanesCount" + nvironment.NewLine);
To write the lines in realtime. This way, your logs would be persisted within every catch..
I also want to point out, that there are very mature Frameworks for Logging. For example NLog or Log4net to name two of the more popular ones.
Upvotes: 1