Incorrect stacktrace by rethrow

前端 未结 12 1383
不知归路
不知归路 2020-11-29 01:49

I rethrow an exception with \"throw;\", but the stacktrace is incorrect:

static void Main(string[] args) {
    try {
        try {
            throw new Exce         


        
12条回答
  •  -上瘾入骨i
    2020-11-29 02:44

    I think this is less a case of stack trace changing and more to do with the way the line number for the stack trace is determined. Trying it out in Visual Studio 2010, the behaviour is similar to what you would expect from the MSDN documentation: "throw ex;" rebuilds the stack trace from the point of this statement, "throw;" leaves the stack trace as it as, except that where ever the exception is rethrown, the line number is the location of the rethrow and not the call the exception came through.

    So with "throw;" the method call tree is left unaltered, but the line numbers may change.

    I've come across this a few times, and it may be by design and just not documented fully. I can understand why they may have done this as the rethrow location is very useful to know, and if your methods are simple enough the original source would usually be obvious anyway.

    As many other people have said, it usually best to not catch the exception unless you really have to, and/or you are going to deal with it at that point.

    Interesting side note: Visual Studio 2010 won't even let me build the code as presented in the question as it picks up the divide by zero error at compile time.

提交回复
热议问题