开发者

Handling Exceptions in Unnatended Services

开发者 https://www.devze.com 2023-03-16 06:40 出处:网络
Edit: Please note that this is not related to my previous question. It\'s another subject. I am writing an application which will be run every 30 seconds or so to do some unnatended work in a databas

Edit: Please note that this is not related to my previous question. It's another subject.

I am writing an application which will be run every 30 seconds or so to do some unnatended work in a database. It requires absolutely no supervision or user/admin interaction. It requires, however, certain parameters to be correctly defined in its App.config file and the database to be accessible upon application start. Furthermore, all exceptions which may eventualy occur need to be logged, but the program can then quit nicely for it will be exec开发者_StackOverflow中文版uted 30 seconds after... The only thing which need to be done in this interval is, then, ensure the database is accessible and all the parameters are correct. That said, is it acceptable/correcto to code the whole behaviour in a method DoWork(), without any exception handling inside the method, and then put this in the Main() method?

try
{
     DoWork();
}
catch (Exception ThisException)
{
    /* Log exception. */
}


That should be OK for most examples. Like said above closing database connection and cleaning up used resources is not something to skip. Keeping around open file handles can be bad and block new runs.

Furthermore there are some fatal exceptions (OutOfMemory,RunTimeException etc) that should be logged or raise some form of alert.


It depends what DoWork() does.

If you are opening and closing files or database connection for example you will need specific error handling to dispose of these resources safely.

There certainly is no harm in having a "catch all" try catch like that as well though.


Error handling needs to be specific. If you anticipate your configurations could be wrong, do a check there instead of throwing an exception. If it needs to throw an exception, write a try...catch specifically for that. What do you want to do if a config is wrong? Shut down the service? Use a default setting?

Having a catch all can be dangerous as any exception thrown and caught by the CLR will get caught in that block. If you catch an exception the idea is to handle it in some way. What happens if that exception is an out of memory exception? File IO? or DB?

Some MSDN article to backup what I'm saying:

http://msdn.microsoft.com/en-us/library/xtd0s8kd.aspx

http://msdn.microsoft.com/en-us/library/seyhszts.aspx

0

精彩评论

暂无评论...
验证码 换一张
取 消