Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the best way to re-use exception handling logic in C#?

Tags:

c#

I have two functions that have different enough logic but pretty much the same exception handling:

public void DoIt1  // DoIt2 has different logic but same exception handling
{
    try
       ... DoIt1 logic
    catch (MySpecialException myEx)
    {
       Debug.WriteLine(myEx.MyErrorString);
       throw;
    }
    catch (Exception e)
    {
       Debug.WriteLine(e.ToString());
       throw;
    }
}

It is not possible to use a single entry point for DoIt1 and DoIt2, because they are called in from outside. Is Copy/Pase (for the exception block) the best approach?

like image 478
Sergey Aldoukhov Avatar asked Jun 25 '09 22:06

Sergey Aldoukhov


1 Answers

It depends... if there is that much commonality, you could pass in the thing to do as a parameter - either as an interface or a delegate:

void Foo(Action thingToDo) {
    if(thingToDo == null) throw new ArgumentNullException("thingToDo");
    try {
        thingToDo();
    } catch {...} // lots of
}

And call as:

Foo(delegate { /* logic A */ });

Foo(delegate { /* logic B */ });
like image 188
Marc Gravell Avatar answered Nov 01 '22 23:11

Marc Gravell