C# Error Handling – Nested Try Catch Error Handling with Log Files

cerror handling

Best practice question for error handling in C#?

In our system we will be writing out files, and with each file they will have a corresponding error file. The error file will get written every time even if there are not any errors.

I'm looking at the best way to handle the errors for this. Assuming when we go to write the main CSV file, we would get a number of errors. From permissions on the folder, to a parsing exception when turning a Datatable to a CSV.

If we get a permission error the error log file will fail as well. Would this be done in the exception? in another try catch (which would be bad.. I think).

We would also want to get the exception to place in the error file.

Some pseudo code below (without the try catch in the exception)
or should this be broken down more and using methods, that contain their own Try / Catch that could bubble up the messages to log and write to files.

    Message.log("begin writing file");
        try {
           try { 
              // get data from DB
              // write to CSV file
              // all good, write Empty Error Log file and main file
           } 
           catch(Exception ex) {
              // Write Error File with ex.toCSV
              // write log message.
              Message.log("error : " + ex.ToString());
           }

        } catch (Exception ex) {
             var e = new Exception(string.Format("An unexpected error occurred for file.\r\n{0}", ex.Message));
             Message.log(e);
             throw e.
        }
       Message.log("all files written");

Best Answer

The problem is your logger. The logger should not throw errors. If there is any error in logger try to resolve it best in logger code, by changing the log location or by disabling the logging, or in extreme by stopping application. Logging is frequent operation, if once it fails it is going to fail again and again. It will be expensive putting try catch around the logging operation every time.

Related Topic