在哪里最好放置代码

Where to best place a throw in code

我正在根据 Web 中的多个来源编写一些异常处理最佳实践。从 Microsoft 网页 (https://msdn.microsoft.com/en-us/library/seyhszts(v=vs.110).aspx) 我得到了推荐:

"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."

我不是很清楚这是什么意思。我们可以说 'throw' 的最佳位置是尽可能靠近相关呼叫吗?这是正确的还是有人有其他建议?

编辑:我会更准确。下面看下面的伪代码

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

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

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

我假设当我在有问题的调用(做某事)之后做其他事情后抛出异常时,我不会得到正确的堆栈跟踪,将我指向正确的行。我说的对吗?

"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."

如果下面的代码没有包含在 try-catch 块中,调试器会给你一个堆栈跟踪,其中最顶层的项目指向 DivideTwoNumbers() 函数,因为它是发生异常的地方.此行之后的所有其他代码:double quotient = DivideTwoNumbers(10, 0); 将不会执行,这意味着您拥有的所有其他 throw 语句都将无用。假设您期望 AnotherFunction() 中出现异常,您会捕获异常还是将 AnotherFunction() 包含在堆栈跟踪中?答案是否定的。

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;
    }