并发和异常处理

时间:2018-03-23 14:08:48

标签: exception concurrency exception-handling uwp c++-cli

所以我有以下代码:

        StorageFolder^ storageFolder = ApplicationData::Current->LocalFolder;

        concurrency::create_task(storageFolder->GetFileAsync(txtfile)).then([](StorageFile^ sampleFile)
        {

            concurrency::create_task(FileIO::AppendTextAsync(sampleFile, New_Program_Data)).then([]() {

            });

        });

我用它来打开文本文件并将一些数据添加到最后。如果文件丢失或损坏或无法打开,我该如何添加异常处理?

我在任务内外尝试了各种 try和catch 语句,但在调试时似乎没有任何效果。应用程序将中断并显示未处理的异常错误。

1 个答案:

答案 0 :(得分:0)

我记得你能够捕捉到这样的例外:

concurrency::create_task(storageFolder->GetFileAsync(txtfile))
.then([](StorageFile^ sampleFile)
{
    // Do whatever you want when successful.
})
.then([] (task<void> previousTask)
{
    // Catch any exceptions of your previous task here.

    try
    {
        // Get the result of the previous task.
        // This also results in exceptions getting thrown.
        previousTask.get();
    }
    catch(Exception^ ex)
    { }
});