gpt4 book ai didi

c# - 在哪里捕获异步代码中的异常?

转载 作者:太空宇宙 更新时间:2023-11-03 21:19:55 24 4
gpt4 key购买 nike

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.

关于c# - 在哪里捕获异步代码中的异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31507895/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com