【发布时间】:2017-06-03 19:53:19
【问题描述】:
我刚刚发现,从 .NET 4.6 开始,Task 对象上有一个新方法 FromException,我想知道在 async 方法中抛出异常的最佳方法是什么。
这里有两个例子:
internal class Program
{
public static void Main(string[] args)
{
MainAsync().Wait();
}
private static async Task MainAsync()
{
try
{
Program p = new Program();
string x = await p.GetTest1(@"C:\temp1");
}
catch (Exception e)
{
// Do something here
}
}
// Using the new FromException method
private Task<string> GetTest1(string filePath)
{
if (!Directory.Exists(filePath))
{
return Task.FromException<string>(new DirectoryNotFoundException("Invalid directory name."));
}
return Task.FromResult(filePath);
}
// Using the normal throw keyword
private Task<string> GetTest2(string filePath)
{
if (!Directory.Exists(filePath))
{
throw new DirectoryNotFoundException("Invalid directory name.");
}
return Task.FromResult(filePath);
}
}
【问题讨论】:
-
在
async方法中抛出异常的最佳方法是throw。但是,您的示例都不是async方法。
标签: c# .net exception async-await task