Reputation: 100
I have successfully been able to open and read files in a UWP
C++
app using the following code:
FileOpenPicker^ openPicker = ref new FileOpenPicker();
openPicker->SuggestedStartLocation= PickerLocationId::DocumentsLibrary;
openPicker->FileTypeFilter->Append(".txt");
create_task(openPicker->PickSingleFileAsync()).then([this](StorageFile^ file)
{
if (file)
{
create_task(FileIO::ReadTextAsync(file)).then([this](Platform::String^ text) {
MessageDialog^ msg = ref new MessageDialog(text);
msg->ShowAsync();
});
}
else
{
MessageDialog^ msg = ref new MessageDialog("Operation cancelled.");
msg->ShowAsync();
}
});
However, if the file content is non-textual e.g. binary, the app crashes. How do I implement error handling? I have tried using try...catch
unsuccessfully.
Upvotes: 0
Views: 80
Reputation: 100
I managed to solve the problem by referring to
The try...catch
should be placed inside the asynchronous task. I was putting it outside. For this, the parameters of create_task()
should be changed:
FileOpenPicker^ openPicker = ref new FileOpenPicker();
openPicker->SuggestedStartLocation= PickerLocationId::DocumentsLibrary;
openPicker->FileTypeFilter->Append(".txt");
create_task(openPicker->PickSingleFileAsync()).then([this](StorageFile^ file)
{
if (file)
{
create_task(FileIO::ReadTextAsync(file)).then([this](task<String^> currentTask) {
try {
String ^text = currentTask.get();
MessageDialog^ msg = ref new MessageDialog(text);
msg->ShowAsync();
}
catch (...) {
MessageDialog^ msg = ref new MessageDialog("Exception handled.");
msg->ShowAsync();
}
});
}
else
{
MessageDialog^ msg = ref new MessageDialog("Operation cancelled.");
msg->ShowAsync();
}
});
When this code is run inside Visual Studio, it will still break showing some hexadecimal symbols when the error occurs. Simply click on Continue
or F5
to get the Exception handled.
error message.
Upvotes: 1