I have a complicated programs which iterate over a bunch of input files does a lot of parsing and calculations and then outputs several other files.
void ParseFiles(string[] files, ProcessingDescription description) {
foreach(string file in files) {
try {
DoComplicatedProcessing(file, description);
}
catch(Exception e) {
LogFailure(file, e);
}
}
DisplayResult();
}
My reason for catching System.Exception in this case is that this could fail for a number of reasons, bugs in the parsing/calculation, illegal values in the input files, permission problems even out-of-memory errors if my assumption that all necessary data could fit in memory turns out to be false.
But in the end I don’t care why it failed. If the program fails for a specific file I want it to log that failure and continue with the next file.
At the end of the session a user might come back and see which files failed and what error message was thrown, sure in many cases the error message might not help the user but it’s better than the program crashing on the first bad file.
I keep hearing “Never catch System.Exception” but I can’t really see any other way of doing this.
You should catch only those exceptions, which you could handle. In this case you can handle any exception, thus there is nothing wrong with this code.