从ContinueWith抛出异常 [英] Throwing exceptions from ContinueWith

查看:999
本文介绍了从ContinueWith抛出异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想换,可以通过异步任务使用 ContinueWith()抛出的异常。如果我刚从延续扔东西的动作似乎工作,但我的调试器宣称的例外是未处理。我做得不对,或这是一个Visual Studio的问题?是否有一个更清洁的方式做到这一点,还是要解决我的调试器停在什么最终是一个处理异常的方法是什么?



下面通行证并打印测试中招包裹例外预期,但是当我调试它抛出新CustomException 行显示为由用户代码未处理的。

  VAR任务= DoWorkAsync()ContinueWith(T =方式> {
抛出新CustomException(包装, t.Exception.InnerException); //调试报告此未处理
},TaskContinuationOptions.OnlyOnFaulted | TaskContinuationOptions.ExecuteSynchronously);

尝试{
task.Wait();
Assert.Fail(预期的工作失败);
}赶上(AggregateException AG){
如果
掷((ag.InnerException是CustomException)!);
}
Console.WriteLine(如预期陷入包装的异常);


解决方案

当启用仅我的代码时,Visual Studio在某些情况下会打破抛出异常的行,并显示一个错误,指出消息异常不是由用户代码来处理。此错误是良性的。您可以按F5继续,看到是体现在这些例子中,异常处理的行为。为了防止Visual Studio中,从打破的第一个错误,只是取消选中工具的仅我的代码复选框,选项,调试,将军。



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


I am trying to wrap the exceptions that can be thrown by an async task using ContinueWith(). If I just throw from the continuation action things seem to work, but my debugger claims 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 to work around my debugger stopping on what is ultimately a handled exception?

The test below passes and prints "caught wrapped exception as expected", but when I debug it the throw new CustomException line shows as "unhandled 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");

解决方案

When "Just My Code" is enabled, Visual Studio in some cases will break on the line that throws the exception and display an error message that says "exception not handled by user code." This error is benign. You can press F5 to continue and see the exception-handling behavior that is demonstrated in these examples. To prevent Visual Studio from breaking on the first error, just uncheck the "Just My Code" checkbox under Tools, Options, Debugging, General.

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

这篇关于从ContinueWith抛出异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆