class WrappedExceptions
{
static void Main()//以熟悉的方式处理异步的异常 在抛出异常时进行包装
{
MainAsync().Wait();
}
static async Task MainAsync()
{
Task<string> task = ReadFileAsync("garbage file");
//"garbage file"
try
{
string text = await task;
Console.WriteLine("File contents: {0}", text);
}
catch (IOException e)
{
Console.WriteLine("Caught IOException: {0}", e.Message);
}
}
static async Task<string> ReadFileAsync(string filename)
{
using (var reader = File.OpenText(filename))
//这里捕获异常
{
return await reader.ReadToEndAsync();
}
}
}
在抛出异常时进行包装
异步方法在调用时永远不会直接抛出异常。异常方法会返回Task或Task<T>,方法内抛出
的任何异常(包括从其他同步或异步操作中传播过来的异常)都将简单地传递给任务。
如果调用者直接等待任务,则可得到一个包含真正异常的AggregateException;但如果调用
者使用await,异常则会从任务中解包。返回void的异步方法可向原始的SynchronizationContext
报告异常,如何处理将取决于上戏闻。
除非在乎为特定的上下文包装和解包异常,否则只需捕获嵌套的异步方法所抛出的异常即可。
输出
Caught IOException: 未能找到文件“garbage file”。 文件路径省略