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.
Personally, I don't see anything wrong with this. You have clearly thought about the problem and have a solution that fits. Any time someone says "Never ..." in software development there is usually a situation were the reverse is true. I guess that is why others say things like, "It is best practice to ..." and "Usually ...". :)
If you are aware that by catching Exception
you will loose granularity of the exception and that you might encounter strange edge cases (memory etc), then it is up to you whether you take on the risk.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With