Blankman
Blankman

Reputation: 266900

throwing an exception in a windows service

Does throwing an exception in a windows service crash the service?

i.e. it will have to be restarted manually

Note: I am throwing the exception from within the catch clause.

Upvotes: 8

Views: 11494

Answers (4)

Matthew Brubaker
Matthew Brubaker

Reputation: 3117

We ran into the problem of an untrapped exception on a child thread causing the service to stop without providing any information about what was causing the exception. We used this method to find out the source of the exception.

You can put a Handler to the service to catch all unhandled exceptions (including all sub threads of the service). In VB.NET, you will need to add a handler for AppDomain.CurrentDomain.UnhandledException. It is likely similar in C#. It will then catch anything that does bubble up past your onStart. You can choose to consume it there or allow it to crash the service from there.

Upvotes: 3

user27414
user27414

Reputation:

If you're throwing the exception in Catch, and there's nothing above it to recatch it, then that will cause your service to stop. The OnStart() method needs a try/catch. If you don't want to stop the service when an Exception occurs, then you need to handle it (log it and move on, or whatever).

My preference woudld be to handle expected exceptions, and to have unexpected exceptions either cause the service to stop, or at least stop/restart automatically. If something unexpected happens your service will be running in an unknown state, and who knows what it will do.

Upvotes: 3

Rich
Rich

Reputation: 896

If the exception is uncaught and bubbles back up to the OnStart() method it will crash the service. You will typically see a message in the Windows Event Log similar to the following:

"The MyServiceName Service service terminated unexpectedly. It has done this x time(s).

Upvotes: 4

Rowland Shaw
Rowland Shaw

Reputation: 38130

Not strictly so -- it'd only cause problems if the exception is unhandled.

Upvotes: 4

Related Questions