1

I am using System.Diagnostics.Trace#TraceError inside a try/catch to trace errors. By looking at the implementation of TraceError, it looks like errors from listeners are not really caught. Does it mean that I should write code like below to avoid errors from logging propagating to the caller:

catch (Exception e) {
    try {
        Trace.TraceError(e);
    } catch {
        // Do nothing
    }
}
oldbam
  • 2,397
  • 1
  • 16
  • 24

1 Answers1

3

Trace.TraceError is not documented to throw exceptions, so no need to catch it. Even though if it is documented to throw exceptions you should never catch an exception and do nothing.

Let the exception raise, only then you'll have a chance to find what's wrong.

See Why is try {...} finally {...} good; try {...} catch{} bad?

Community
  • 1
  • 1
Sriram Sakthivel
  • 72,067
  • 7
  • 111
  • 189
  • 1
    `You should never catch an exception and do nothing` - I highly disagree. If bubbling up the exception has no value, why would you bubble it? If your logging sub system fails for some reason should you crash your whole application? Should you alert the user? Most likely not! Suppress the exception in this case, and let the application continue to do its job. – Philip Pittle Jul 25 '14 at 10:35
  • 2
    @PhilipPittle Come on. It is a general advise to be aware of. That's why I linked the related question. As you said, rules can be changed depending upon the scenario :) btw Why to suppress errors? I'd rather fix it in code if it can be done.. – Sriram Sakthivel Jul 25 '14 at 10:40
  • never say never :). I agree best practice is to do something with the exception. But it's not required in every case. – Philip Pittle Jul 25 '14 at 10:41
  • I want to suppress exceptions, since otherwise they may propagate to an end user. Also, in order to have a robust code, can I really rely on someone's documentation? What if a guy forgot about documenting exceptions? As I have said, I didn't see try/catch in the implementation of Trace – oldbam Jul 25 '14 at 17:08
  • Almost 95% of .net methods will not have try/catch because they don't want to supress exceptions. You can rely on msft's documentation, as we do it. I've never seen they forgot to document any exceptions. If a method/ class doesn't work as documented, then it is a bug. You can report it [here](https://connect.microsoft.com/visualstudio). – Sriram Sakthivel Jul 25 '14 at 17:19