0

I am working in a windows service (using VB.Net) for internal use of my department. When ever a certain type of exception (FooException for now on) is captured, I follow the same logic:

  • Log the exception
  • Send an email to someone.

In order to reuse code and not to copy-paste the same lines in every catch FooException block I have created a FooExceptionHandler method inside my ExceptionHandling class. So I ended up with a code like this:

FooExceptionHandler(fooException)
{
   //log the exception
   try
   {
      //send email
   }
   catch SmtpException
   {
      //log  the smtp exception
   }
}

My question is about how to organize the code. Should this be a static method? Should all the exception handling class be static? Should it be a singleton? Should it be object-oriented?

If the object-oriented case is the best way, should I create a new object in every catch block or is it better to have a class variable?

1 Answer 1

0

The right answer depends on how big your application is and how you test it. If your application is big, modular enterprise application and you use unit-tests, then the only solution you really have is to go object-oriented way.

In that case you create an interface IExceptionHandler, and all client classes consume that interface. You may then use some object-creation pattern like a factory method to create your exception handling objects that implement that interface, or handle it with Dependency injection.

That way you make your production code decoupled from exception-handling mechanism and easily adjust or change exception-handling behaviour in future without touching the code in other classes.

If your application is small and mostly for personal use, then just implement the exception-handling logic the way you feel is most convenient to you.

3
  • 2
    OO is the only way to go for testing is not true, static methods can be injected just fine in any language which supports first class functions or delegates
    – jk.
    Commented Apr 17, 2013 at 11:54
  • Good point. Method injecting via delegates is interesting and perfectly viable approach. I almost forgot that I actualy used it myself. It mixes some functional programming into an object paradigm though, and when used improperly can cause problems or decrease readability of code (just like improper use of objects does in fact). Commented Apr 17, 2013 at 12:15
  • thanks for the answer. I have choosen the OO way. Not only because of our answer but I have also find the code its cleaner and simpler that way, I dont like static methods to much :) Commented Apr 21, 2013 at 17:46

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.