views:

56

answers:

1

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
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
@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
So in that case is it OK to catch(exception e) { //log; throw e; }? I thought that was always a no no
Ziplin
@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
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
@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
Ahhh jeez. I've been living a lie.
Ziplin