Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it good form to catch System.Exception when the reason for failure is unimportant?

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.

like image 483
lyml Avatar asked Jan 16 '23 02:01

lyml


2 Answers

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.

like image 51
Sergey Berezovskiy Avatar answered Jan 25 '23 04:01

Sergey Berezovskiy


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.

like image 21
Davin Tryon Avatar answered Jan 25 '23 04:01

Davin Tryon