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.
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();
}
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With