Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to handle exceptions that are deep in code?

I have a webservice that returns xml.The problem is methods that are executed "deep" in code where a simple return won't stop program execution.

What happens is I set my xml error message in a catch statement but the code will keep executing through the rest of the outer method and overwrite my xml error response.

Is there a design pattern or best practice to get around this?

      Main Program Block                    SomeClass

         execute someMethod()     ---->     public someMethod()
                                            {
                                                    -----> private method()// try / catch error occurred (send back an xml error response)

                                                    // code execution continues and does some stuff and generates an xml response
                                                    <request>
                                                    <success>true</success>
                                                    </request>
                                            }
like image 621
chobo Avatar asked Jan 21 '26 01:01

chobo


2 Answers

You can re-throw the exception. For example:

    private static string errorMessage;
    static void Main(string[] args)
    {
        try
        {
            Test1();
        }
        catch (Exception ex) 
        {
            Console.WriteLine("Something went wrong deep in the bowels of this application! " + errorMessage );
        }

    }

    static void Test1()
    {
        try
        {
            Test2(1);
            Test2(0);   
        }
        catch (Exception ex)
        {
            errorMessage = ex.Message;
            throw;
        }
    }

    static string Test2(int x)
    {
        if (x==0) throw new ArgumentException("X is 0!");
        return x.ToString();
    }

An additional piece of advice: When re-throwing an exception, use throw;, not throw ex;, in order to preserve the stack trace. See this for some more information on the subject.

like image 134
Daniel Mann Avatar answered Jan 23 '26 21:01

Daniel Mann


catch (Exception)
{
    // Set errors here
    throw;
}

This will rethrow the exception. Is that what you're looking for?

like image 31
pdr Avatar answered Jan 23 '26 20:01

pdr



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!