Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Additional try statement in catch statement - code smell?

Situation:

My application need to process the first step in the business rules (the initial try-catch statement). If an certain error occurs when the process calls the helper method during the step, I need to switch to a second process in the catch statement. The back up process uses the same helper method. If an same error occurs during the second process, I need to stop the entire process and throw the exception.

Implementation:

I was going to insert another try-catch statement into the catch statement of the first try-catch statement.

//run initial process
try
{
    //initial information used in helper method
    string s1 = "value 1";

    //call helper method
    HelperMethod(s1);
}
catch(Exception e1)
{
    //backup information if first process generates an exception in the helper method
    string s2 = "value 2";

    //try catch statement for second process.
    try
    {
        HelperMethod(s2);
    }
    catch(Exception e2)
    {
        throw e2;
    }
}

What would be the correct design pattern to avoid code smells in this implementation?

I caused some confusion and left out that when the first process fails and switches to the second process, it will send different information to the helper method. I have updated the scenario to reflect the entire process.

like image 659
Michael Kniskern Avatar asked Dec 08 '09 16:12

Michael Kniskern


1 Answers

If the HelperMethod needs a second try, there is nothing directly wrong with this, but your code in the catch tries to do way too much, and it destroys the stacktrace from e2.

You only need:

try
{
    //call helper method
    HelperMethod();
}    
catch(Exception e1)
{
    // maybe log e1, it is getting lost here
    HelperMethod();
}
like image 114
Henk Holterman Avatar answered Oct 01 '22 16:10

Henk Holterman