4

I have created a .net c# windows service that runs multiple tasks. I included exception handling in it but I would like to set up a global handler to catch unhandled exceptions in the windows service, how can I do this?

amateur
  • 43,371
  • 65
  • 192
  • 320

1 Answers1

6

I included exception handling in it but I would like to set up a global handler to catch unhandled exceptions in the windows service

You could use AppDomain.UnhandledException. In your case however, your entire call to your service can be wrapped in a try/catch block. Since you haven't provided details for what you plan to do with this unhandled exception, your correct path I think in this case is to let the service crash.

try
{
   MainCallToYourService();
}
catch (Exception)
{
   //it's probably too late to do anything useful here, try to log and die
}

Keep in mind though that the problem in doing this is that in a lot of cases, your application's state is corrupt by the time this event is raised. Your best bet is to try and log it and get out.

Bryan Crosby
  • 6,486
  • 3
  • 36
  • 55
  • This is the correct answer. Lots of people get exception handling wrong. There is absolutely no point in catching exceptions that you can't handle. When you get an unhandled global exception, the best thing you can do is crash (since that is, in fact, what has already happened). If you just want to log it, use `AppDomain.UnhandledException`, as you mentioned. – Cody Gray - on strike May 15 '12 at 22:34
  • 1
    I understand this, but all I want to do is to be able to log the exception so I have a track of it. I tried AppDomain.UnhandledException and I set up the event handler when the service is created, but the event never gets fired. Any idea why? – amateur May 15 '12 at 23:04
  • @amateur: are you creating other threads or do you just have a single-threaded service? – Bryan Crosby May 15 '12 at 23:22
  • Its a multi threaded windows service so other threads being created. – amateur May 15 '12 at 23:24
  • @amateur: You will need to post some relevant code (hopefully including where you *think* this exception may be occurring, since it is not handled). It's pretty difficult to diagnose this without posting some code. – Bryan Crosby May 15 '12 at 23:36