如何处理异步函数中的异常UWP App GetFileFromPathAsync(path);

时间:2017-06-29 18:46:17

标签: c++ exception asynchronous visual-c++ uwp

此代码在抛出时不会捕获AccessDeniedException。

为什么?

没有任何异常处理程序会捕获它。我完全遵循了文档。

auto fileOp = StorageFile::GetFileFromPathAsync(filePath);
auto fileTask = create_task(fileOp);    
auto c1 = fileTask.then([](StorageFile^ file) {
             //...
            }).then([](task<StorageFile^> t) {
                try {
                    auto ident = t.get();
                }
                catch (const std::exception &e) {
                    auto msg = ref new MessageDialog("File not found.");
                }
                catch (AccessDeniedException^ e) {
                    auto msg = ref new MessageDialog("Access denied.");
                }
                catch (Exception^ e) {
                    auto msg = ref new MessageDialog("Unknown errer.");
                }
            });

1 个答案:

答案 0 :(得分:0)

要处理GetFileFromPathAsync方法中引发的异常,您可以尝试使用以下代码:

auto fileOp = StorageFile::GetFileFromPathAsync(filePath);
auto fileTask = create_task(fileOp);
auto c1 = fileTask.then([](task<StorageFile^> t) {
    try
    {
        StorageFile^ file = t.get();
        ///...
    }
    catch (AccessDeniedException^)
    {
        auto msg = ref new MessageDialog("Access denied.");
        create_task(msg->ShowAsync());
    }
    catch (Exception^ e) {
        auto msg = ref new MessageDialog(e->Message);
        create_task(msg->ShowAsync());
    }
});