title: How to catch an unhandled exception in Windows Azure (Worker) Role
body: <p>I'm trying to catch all unhandled exceptions in my worker role. I tried putting a <code>try</code>-<code>catch</code> block into the <code>Run()</code> method (as suggested <a href="http://social.msdn.microsoft.com/Forums/en/windowsazuretroubleshooting/thread/11019f45-0ab6-403b-8908-fa40766af875" rel="noreferrer">here</a>) but with no success.</p>
  
  <pre><code>public override void Run()
  {
    try
    {
      base.Run();
    }
    catch (Exception ex)
    {
      Trace.TraceError("Unhandled Exception: {0}", ex);    
      throw ex;
    }
  }
  </code></pre>
  
  <p>The role hosts a WCF service, so there is no other logic inside the <code>Run()</code> method. Is there another possibility to catch exceptions at this level?</p>
  
  <p><strong>Update 1</strong>
  To clarify the problem: The role self hosts a WCF service (initialized in <code>OnStart()</code>) where some operations are background operations. When the service is called and that method throws an unexpected exception, I like to catch that to write it to the log.</p>
  
  <p><strong>Solution:</strong>
  Obviously it is like in a normal C# application:
  Just add a handler to the <code>UnhandledException</code> event like this</p>
  
  <pre><code>AppDomain.CurrentDomain.UnhandledException +=
    new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);
  </code></pre>
  
  <p>inside the <code>OnStart()</code> of the Role. I was so focused on Azure that I supposed this couldn't work after all, that I didn't even try it :-)</p>