Why does stack get truncated in Exception.StackTrace?

前端 未结 4 1194
梦如初夏
梦如初夏 2021-02-05 18:31

Why does the high part of the stack (in Exception.StackTrace) gets truncated? Let\'s see a simple example:

public void ExternalMethod()
{
  InternalMethod();
}         


        
4条回答
  •  南笙
    南笙 (楼主)
    2021-02-05 19:12

    Ok, now I see what your getting at... Sorry for my confusion on the inlining thing.

    The 'stack' in a caught exception is only a delta from the currently executing catch block to where the exception was thrown. Conceptually this behavior is correct in that the Exception.StackTrack tells you where the exception occurred within the context of this try/catch block. This allows exception stacks to be forwarded across 'virtual' calls and still maintain accuracy. One classic example of this being done is .Net Remoting exceptions.

    Thus if you want a complete stack report in the catch block you would add the current stack to the exception's stack as in the example below. The only problem is this can be more expensive.

        private void InternalMethod()
        {
            try
            {
                ThrowSomething();
            }
            catch (Exception ex)
            {
                StackTrace currentStack = new StackTrace(1, true);
                StackTrace exceptionStack = new StackTrace(ex, true);
                string fullStackMessage = exceptionStack.ToString() + currentStack.ToString();
            }
        }
    

提交回复
热议问题