what can lead throw to reset a callstack (I'm using “throw”, not “throw ex”)

后端 未结 3 1186
别跟我提以往
别跟我提以往 2020-11-30 00:35

I\'ve always thought the difference between \"throw\" and \"throw ex\" was that throw alone wasn\'t resetting the stacktrace of the exception.

Unfortunately, that\'s

3条回答
  •  温柔的废话
    2020-11-30 01:30

    You should read this article:

    • Rethrowing exceptions and preserving the full call stack trace

    In short, throw usually preserves the stack trace of the original thrown exception, but only if the exception didn't occur in the current stack frame (i.e. method).

    There is a method PreserveStackTrace (shown in that blog article) that you use that preserves the original stack trace like this:

    try
    {
    
    }
    catch (Exception ex)
    {
        PreserveStackTrace(ex);
        throw;
    }
    

    But my usual solution is to either simply to not catch and re throw exceptions like this (unless absolutely necessary), or just to always throw new exceptions using the InnerException property to propagate the original exception:

    try
    {
    
    }
    catch (Exception ex)
    {
         throw new Exception("Error doing foo", ex);
    }
    

提交回复
热议问题