我有一段代碼可以正確地從http URI加載圖片,當URI有效但我不知道如何捕獲異常OpenAsync在URI無效時拋出(結果在404)。如何處理來自StorageFile :: OpenAsync的異常,當URI不好時
問題是,當包含對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是否有效? – 2013-04-25 14:58:51
第三個不會被捕獲,因爲lambda排隊由then()調用在不同的執行上下文中執行。第三種方法是在then()調用發生問題時嘗試將lambda添加到隊列中。調用then()函數的函數會在lambda表達式實際執行之前退出。 – 2013-04-25 15:11:48