title: How to catch/observe an unhandled exception thrown from a Task
body: <p>I'm trying to log / report all unhandled exceptions in my app (error reporting solution). I've come across a scenario that is always unhandled. I'm wondering how would I catch this error in an unhandled manner. Please note that I've done a ton of research this morning and tried a lot of things.. Yes, I've seen <a href="http://msdn.microsoft.com/en-us/library/dd537614.aspx">this</a>, <a href="http://blogs.msdn.com/b/pfxteam/archive/2009/05/31/9674669.aspx">this</a> and many more. I'm just looking for a generic solution to log unhandled exceptions.</p>
  
  <p>I have the following code inside of a console test apps main method:</p>
  
  <pre><code>Task.Factory.StartNew(TryExecute);
  </code></pre>
  
  <p>or</p>
  
  <pre><code>Task.Run((Action)TryExecute);
  </code></pre>
  
  <p>as well as the following method:</p>
  
  <pre><code>private static void TryExecute() {
     throw new Exception("I'm never caught");
  }
  </code></pre>
  
  <p>I'm already tried wiring up to the following in my app, but they are never called.</p>
  
  <pre><code>AppDomain.CurrentDomain.UnhandledException
  TaskScheduler.UnobservedTaskException
  </code></pre>
  
  <p>In my Wpf app where I initially found this error I also wired up to these events but it was never called.</p>
  
  <pre><code>Dispatcher.UnhandledException
  Application.Current.DispatcherUnhandledException
  System.Windows.Forms.Application.ThreadException
  </code></pre>
  
  <p>The only handler that is called ever is:</p>
  
  <pre><code>AppDomain.CurrentDomain.FirstChanceException
  </code></pre>
  
  <p>but this is not a valid solution as I only want to report uncaught exceptions (not every exception as FirstChanceException is called before any catch blocks are ever executed / resolved.</p>