Throwing Exceptions from ContinueWith

I am trying to wrap exceptions that can be thrown by an asynchronous task using ContinueWith(). If I just drop the continuation action, everything works, but my debugger claims that the exception is unhandled. Am I doing something wrong or is this a Visual Studio problem? Is there a cleaner way to do this, or a way around my debugger, focusing on what the exception is ultimately handled?

The test below passes and prints a "caught wrapped exception as expected", but when I debug it, the line is throw new CustomExceptiondisplayed as "not processed by user code".

var task = DoWorkAsync().ContinueWith(t => {
    throw new CustomException("Wrapped", t.Exception.InnerException);  // Debugger reports this unhandled
}, TaskContinuationOptions.OnlyOnFaulted | TaskContinuationOptions.ExecuteSynchronously);

try {
    task.Wait();
    Assert.Fail("Expected work to fail");
} catch (AggregateException ag) {
    if (!(ag.InnerException is CustomException))
        throw;
}
Console.WriteLine("Caught wrapped exception as expected");
+5
source share
2

" ", Visual Studio , , " ". . F5 , . Visual Studio, " " "", "", "", "".

http://msdn.microsoft.com/en-us/library/dd997415.aspx

+9

, "" , , , . DoWorkAsync - , , "" :

DoWorkAsync().ContinueWith(t=>{
 Console.WriteLine("Error occurred: " + t.Exception);
}, TaskContinuationOptions.OnlyOnFaulted);

, "" async, :

var task = DoWorkAsync();

task.Wait();
if(task.Exception != null)
{
  Console.WriteLine("Error occurred: " + task.Exception);
}

, - :

var task = DoWorkAsync().ContinueWith(t=>{
 if(t.Exception.InnerExceptions[0].GetType() == typeof(TimeoutException))
 {
     throw new BackoffException(t.Exception.InnerExceptions[0]);
 }
}, TaskContinuationOptions.OnlyOnFaulted);

BackoffException :

if(task.IsFaulted)
{
   Console.WriteLine(task.Exception.InnerExceptions[0]);
   // TODO: check what type and do something other than WriteLine.
}
+4

All Articles