如何处理异步函数中的异常UWP应用程序getFileFrompathAsync(path);

How to handle exception in async function UWP App GetFileFromPathAsync(path);

本文关键字:应用程序 UWP 异常 getFileFrompathAsync path 函数 何处理 处理 异步      更新时间:2023-10-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.");
                }
            });

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