-2

So I have the following code:

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

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

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

            });

        });

Which I use to open a text file and append some data to the end. How can I add exception handling in the event that the file is missing or corrupt or can't be opened?

I've tried various try and catch statements inside and outside the tasks, but nothing seems to work when debugging. The application will break and show an unhandled exception error.

Gavin Hannah
  • 161
  • 9
  • 1
    You need to use `task`s as arguments of countinuation function to get exceptions, if you use the `StorageFile^` you'll not be able to get the exceptions. See https://msdn.microsoft.com/en-us/library/dd997692.aspx and https://stackoverflow.com/a/15123425/8918119 – Mihayl Mar 23 '18 at 14:43

1 Answers1

0

As I remember you're able to catch exceptions like this:

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)
    { }
});
Wum
  • 306
  • 1
  • 10