Search code examples
visual-studio-2010exceptionunhandled-exception

Exception treated as user-unhandled even though it's handled


Short version:

Why does Visual Studio tell me that the code has thrown a user-unhandled exception, even though I catch the exception?

Longer version:

I'm using Entity Framework together with Microsoft's transient fault handling framework:

My Entity Framework class is partial, and I have my own method SaveChangesWithRetries where I perform the retry-logics:

public partial class EfContext
{
    public virtual void SaveChangesWithRetries()
    {
       var retryPolicy = RetryPolicyFactory.GetDefaultSqlCommandRetryPolicy();
       retryPolicy.ExecuteAction(() =>
                       {
                          SaveChanges();
                       });
    }
 }

My code which uses this function may look as follows:

try
{
    context.SaveChangesWithRetries();
}
catch (OptimisticConcurrencyException)
{
    continue;
}

Even though I catch the OptimisticConcurrencyException exception, Visual Studio stops the debugger and tell me that the call to ExecuteAction() threw an user-unhandled exception. When this happens, the debugger stop within the EfContext class. If I press F10, the debugger moves to the catch (OptimisticConcurrencyException).

I don't understand why VS2010 tells me that there was a user-unhandled exception even though I have a catch and even though my catch catches the exception.


Solution

  • Figured out what was causing this.

    1. Our code started a try/catch clause
    2. Our code called Transient Fault Handling Framework (TFHF)
    3. TFHF called our code (via lambda expression9
    4. Our code threw exception

    Since TFHF was built in release, the .NET Framework did not understand that our own code catched the exception in step 0, which was thrown in step 3.