Search code examples
c#multithreadingdelegateslambdathrow

WPF Dispatcher Thread- Using lambda expression and throw to dispatch exception to UI thread


try
{
    string s = null;
    s.PadLeft(10);
}
catch (Exception ex)
{
    // send exception to UI Thread so it can be handled by our global exception 
    // handler
    Application.Current.Dispatcher.Invoke(DispatcherPriority.Send, 
        new Action<Exception>(e => { throw ex; }), ex);
}

As you can see, 'throw ex' will truncate the stacktrace, I would like to use throw instead of throw ex but I get:

A throw statement with no arguments is not allowed outside of a catch clause.

How can I use lambda expression to throw the exception without truncating stacktrace?


Solution

  • Why don't you just create a new Exception with the old exception as InnerException?

    e => throw new WhateverException("your message", ex);
    

    That preserves the original stacktrace.