Task task = AsyncMethod();
// do other stuff
await task;
AsyncMethod() 可以抛出异常。我是否将 try-catch 放在方法调用、await 或两者周围?
请您参考如下方法:
为了避免关于应该在何处进行异常处理的争论,我只是将您的问题稍微更改为:在哪里可以捕获从 AsyncMethod 方法抛出的异常。
答案是:你在哪里等待它。
假设您的 AsyncMethod 方法看起来像这样:
private async Task AsyncMethod()
{
// some code...
throw new VerySpecificException();
}
...然后你可以这样捕获异常:
Task task = AsyncMethod();
// do other stuff
try
{
await task;
}
catch(VerySpecificException e) // nice, I can use the correct exception type here.
{
// do something with exception here.
}
只需测试一下,您就会看到 await 关键字是如何完成从返回的 Task 中解包和抛出异常的所有工作,感觉非常棒编写 try-catch block 很自然。
相关文档:try-catch .
注意异步方法中的异常部分说的是什么:
To catch the exception, await the task in a try block, and catch the exception in the associated catch block.
