【发布时间】:2013-04-25 14:53:20
【问题描述】:
我有一段代码可以在 URI 有效时从 http URI 正确加载图像,但我不知道如何捕获 OpenAsync 在 URI 无效时抛出的异常(结果为 404)。
问题是当包含 OpenAsync 调用的 lambda 退出时,会抛出异常;在 try/catch 块中不会抛出异常。
问题是:
捕获 StorageFile::OpenAsync 抛出的异常的正确方法是什么?
auto bm = ref new BitmapImage();
try {
Uri^ uri = ref new Uri("http://invaliduri.tumblr.com/avatar/128");
auto task = Concurrency::create_task(CreateStreamedFileFromUriAsync("temp-web-file.png", uri, nullptr));
task.then([] (StorageFile^ file) {
try {
return file->OpenAsync(FileAccessMode::Read);
} catch (...) {
// this does not catch the exception because the exception
// occurs after this lambda is exitted
}
}).then([bm](IRandomAccessStream^ inputStream) {
try {
return bm->SetSourceAsync(inputStream);
} catch (...) {
// this does not catch the exception because the exception
// occurs before this lambda is entered
}
});
} catch (...) {
// and obviously this would not catch the exception
}
【问题讨论】:
-
为什么第三个
catch抓不到?完整的代码在其匹配的try块中。Uri^ uri有效吗? -
第三个不会捕获,因为 lambda 被 then() 调用排队以在不同的执行上下文中执行。第三个问题是当 then() 调用尝试将 lambda 添加到队列时出现问题。调用 then() 函数的函数在 lambda 实际执行之前很久就退出了。
标签: c++ file-io windows-8 exception-handling concurrency-runtime