.NET 4.6以降では、オブジェクトに新しいメソッドFromException
があり、例外をスローするにはどうすればよいか疑問に思っていました。 async
方法非同期メソッド(Task.FromException)で例外をスローする方法
ここでは二つの例:
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'メソッドではありません。 –