【问题标题】:How to handle exception in async function UWP App GetFileFromPathAsync(path);如何处理异步函数 UWP App GetFileFromPathAsync(path) 中的异常;
【发布时间】:2017-06-29 18:46:16
【问题描述】:

此代码在抛出 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.");
                }
            });

【问题讨论】:

  • 我无法让代码工作,不,但我能够找到使用 FileIO 的工作。我仍然不明白这里出了什么问题。
  • 这很奇怪,我的代码在我这边运行良好。您是否尝试过一个新的空白 C++ 项目?或者您能否分享minimal reproducible example,以便我们知道出了什么问题?

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


【解决方案1】:

要处理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());
    }
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-11-20
    • 1970-01-01
    • 1970-01-01
    • 2019-08-29
    • 2019-08-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多