How to continue a loop after an error?
.net-4.5, c#
Solution
Don't use `try..catch` as a panacea outside the for. Remove it from there and put it around those single instructions that you know may cause trouble.
The tighter they are the better. You will then be able to handle that case without breaking out of the entire loop or procedure:
for(...)
{
// procedural code
try {
// least possible problem code
} catch(Exception ex) {
// log/report error 1
// use continue/break to continue with next cycle or break out of the loop
Log.Message("Exception (in big loop #01): " + ex.Message);
}
// procedural code
try {
// least possible problem code
} catch(Exception ex) {
// log/report error 2
// use continue/break to continue with next cycle or break out of the loop
Log.Message("Exception (in big loop #02):" + ex.Message);
}
// procedural code
}
This way you'll also be able to distinguish where the exception occurred.
To log the exception you'll have to implement the `Log` class this way:
using System.IO;
public class Log
{
public static void Message(string message)
{
using (StreamWriter writer = File.AppendText("path_to_dir\\log.txt"))
{
writer.WriteLine(message);
}
}
}
This `Log` class is very very basic and can be improved in following ways:
- don't use static methods
- don't use singleton, inject a logger object into the big-loop-function
- add time and date in front of each line
- add standard facility and severity (best if taken from syslogd)
- allow to also send email if severity is above threshold level
- allow for log rolling based on time, lines or file size
- what happens if an exception occurs while logging an exception? a meta-exception!?
- much more
What I put here is just to give you an idea about logging errors. It is a quite wide area of expertise.
Problem
I have an application that runs a big loop where it reads data, writes to a PDF and e-mails the files, all in one swoop. Sometimes, an error will appear and I have to retrace back to what caused the error. Basically the whole loop is in a Try/Catch block. There are two loops, basically (in pseudo-code): ``` try // Loop 1 process 1 // Loop 2 process 2 catch // Message box error ``` Is there a way I can continue this loop and just skip the error? Maybe save a log with the exception so I can save it later?