Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to avoid exceptions catches copy-paste in .NET

Working with .NET framework I have a service with a set of methods that can generates several types of exceptions: MyException2, MyExc1, Exception... To provide proper work for all methods, each of them contains following sections:

[WebMethod]
void Method1(...)
{
    try
    {
        ... required functionality
    }
    catch(MyException2 exc)
    {
        ... process exception of MyException2 type
    }
    catch(MyExc1 exc)
    {
        ... process exception of MyExc1 type
    }
    catch(Exception exc)
    {
        ... process exception of Exception type
    }
    ... process and return result if necessary
}

It is very boring to have exactly same stuff in EACH service method (each method has different set of parameters) with exactly same exceptions processing functionality...

Is there any possibility to "group" these catch-sections and use only one line (something similar to C++ macros)? Probably something new in .NET 4.0 is related to this topic?

Thanks.

P.S. Any thoughts are welcome.

like image 372
Budda Avatar asked Jun 17 '10 18:06

Budda


2 Answers

If the exception handling is exactly the same in all of your methods, you could do something like:

void CallService(Action method)
{
    try
    {
        // Execute method
        method();
    }
    catch(MyException2 exc)
    {
        ... process exception of MyException2 type
    }
    catch(MyExc1 exc)
    {   
        ... process exception of MyExc1 type
    }
    catch(Exception exc)
    {
        ... process exception of Exception type
    }
}

Then, you could just rewrite your client code to do:

int i = 3;
string arg = "Foo";
this.CallService( () => this.Method1(i) );
this.CallService( () => this.Method2(arg, 5) );

This allows your Method1 and Method2 methods to be simply:

void Method1(int arg)
{
    // Leave out exception handling here...
    ... required functionality  
    ... process and return result if necessary
}

void Method2(string stringArg, int intArg)
{
    // Leave out exception handling here...
    ... required functionality  
    ... process and return result if necessary
}
like image 79
Reed Copsey Avatar answered Sep 19 '22 22:09

Reed Copsey


Why not just factor the code into a helper method to do it for you (you can add whatever new exceptions you need in the future to HandleException as well, which makes it quite scalable)?

try
{
    ... required functionality
}
catch (Exception e)
{
    HandleException(e);
    throw; // only if you need the exception to propagate to caller
}


private void HandleException(Exception e)
{
    if (e is MyException2)
    {
        ... process exception of MyException2 type
    }
    else if (e is MyExc1)
    {
        ... process exception of MyExc1 type
    }
    else
    {
        ... process exception of Exception type
    }
}
like image 38
dcp Avatar answered Sep 20 '22 22:09

dcp