How can I preserve the stack trace when exception is thrown on non

Doing this is bad form because it doesn't preserve a stack trace:

try { /*... some code that can throw an exception ...*/ }
catch (Exception e)
{
    throw e; // ...Use "throw;" by itself instead
}

However, if the exception is caught on a non-UI thread, I want to do raise it back up to the UI and handle it so the user gets the message like so:

try { /*... some code that can throw an exception ...*/ }
catch (Exception e)
{
    Dispatcher.Invoke((Action)(() => { throw; }));
}

However, I can't use the throw keyword by itself here because the C# lexer (correctly) doesn't think the throw statement is inside of a catch . I have to instead do:

try { /*... some code that can throw an exception ...*/ }
catch (Exception e)
{
    Dispatcher.Invoke((Action)(() => { throw e; }));
}

and re-throw the exception, which loses its stack trace.

Is there any (easy) way to get around this (I could always package the stack trace at the time the exception is ready to switch threads, but that seems hokey)?

Note: I saw this thread but it's similar in title only, not content.


The usual way to do this is to throw a new exception, with the original included as InnerException . Exception has a special constructor for this.

But if you really want to do this and you're on .Net 4.5, you can use ExceptionDispatchInfo to capture the stack trace of the exception and then rethrowing it somewhere else without resetting the stack trace. But in most situations, using the old method of wrapping the exception in a new one is probably better.

链接地址: http://www.djcxy.com/p/69134.html

上一篇: 涉及枚举类型的对象继承

下一篇: 如何在非抛出异常时保留堆栈跟踪