How to keep a stack trace when an exception is thrown in a thread other than the UI

This is a bad form because it does not save the 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 in a thread other than the UI, I want to make it back to the user interface and process it so that the user receives the message like this:

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

However, I cannot use the throw keyword here because the C # lexer (correctly) does not consider the throw statement to be inside the catch . I have to do the following:

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

and rethrow the exception that loses the stack trace.

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

Note. I saw this stream , but it only looks like the header, not the content.

+7
source share
1 answer

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

But if you really want to do this, and you are on .Net 4.5, you can use ExceptionDispatchInfo to grab the trace of the exception stack and then drag it to another location without resetting the stack trace. But in most cases, using the old method of wrapping exceptions in the new is probably better.

+4
source

All Articles