Search code examples
c#exceptionthrow

Where to best place a throw in code


I'm writing some exception handling best practices based on several sources in the web. From the Microsoft webpage (https://msdn.microsoft.com/en-us/library/seyhszts(v=vs.110).aspx) I got the recommendation:

"The stack trace begins at the statement where the exception is thrown and ends at the catch statement that catches the exception. Be aware of this fact when deciding where to place a throw statement."

I'm not really shure what this means. Can we say the best place for a 'throw' is as close to the call in question as possible? Is this correct or does anybody have other suggestions?

Edit: I will be more precise. See the following pseudo code below

    // do something that assignes a value to 'someValue'

    // do more that's not related to the call above

    if (someValue == whatever)
    {
        throw new MyException();
    }

I assume when I'm throwing the exception after doing something else after the call in question (do something), I will not get the correct stack trace pointing me to the right line. Am I right?


Solution

  • "The stack trace begins at the statement where the exception is thrown and ends at the catch statement that catches the exception. Be aware of this fact when deciding where to place a throw statement."

    If the following code is not wrapped inside a try-catch block, the debugger would give you a stack trace where the topmost item points to the DivideTwoNumbers() function since it is where the exception has occurred. All other code after this line: double quotient = DivideTwoNumbers(10, 0); will not executed which means all other throw statements you have will be useless. Suppose you are expecting an exception inside AnotherFunction(), do you get to catch the exception or will AnotherFunction() be included in the stack trace? The answer is NO.

    static void Main(string[] args)
        {
            try
            {
                double quotient = DivideTwoNumbers(10, 0);
                AnotherFunction();
    
            }
    
            catch (DivideByZeroException ex)
            {
                Console.WriteLine(ex.Message);
            }
    
            Console.ReadLine();
        }
    
        static int DivideTwoNumbers(int dividend, int divisor)
        {
            if (divisor == 0)
                throw new DivideByZeroException();
            return dividend / divisor;
        }