I have a multithreaded windows service that will unpredictably stop running once every 24 hours or so. I am writing to the event log and that's going through just fine, but whenever the service crashes there are no messages in the event log (even that the service stopped, despite having AutoLog=true). Is there a way to have uncaught exceptions written straight to the log, even if they aren't in the original thread?
+1
A:
First of all, threads that you spawn should have a top level try { } ... catch { }
block that catches (and, if appropriate, either swallows or rethrows) exceptions thrown on them. Apart from that, you can use the AppDomain.UnhandledException
event to catch any unhandled exceptions and log them out.
Adam Robinson
2010-06-12 18:40:01
What would you catch in a top level try-catch? At that level I'm assuming you aren't sure what you're catching, and in that case I thought you weren't supposed to be catching anything?
Ziplin
2010-06-15 18:31:10
@Ziplin: It would be a `catch` and `throw` scenario. While you can't recover from the exception, catching it at a top level allows you to log information (or something similar) then rethrow it.
Adam Robinson
2010-06-15 18:38:45
So in that case is it OK to catch(exception e) { //log; throw e; }? I thought that was always a no no
Ziplin
2010-06-15 20:33:07
@Ziplin: Not `throw e;` just `throw;`. Including the caught exception as part of a throw statement is a no-no because it resets the stack trace; just calling `throw` will not do that.
Adam Robinson
2010-06-16 01:25:23
My mistake, I knew `throw` is correct. I was asking about catching a System.Exception, which is always supposed to be a no no (I think).
Ziplin
2010-06-17 23:28:52
@Ziplin: It's a no-no to catch and "swallow" them. There's nothing wrong with catching a general exception (at a high level in the application) for the purpose of logging it then rethrowing it.
Adam Robinson
2010-06-18 02:01:23
Ahhh jeez. I've been living a lie.
Ziplin
2010-06-18 13:38:45