问题
I am using the following code in my Windows 8 app function to catch an error and display an Message Dialog
catch (Exception ex)
{
MessageDialog err = new MessageDialog("Error");
await err.ShowAsync();
}
But I get an error "cannot await in the body of a catch clause".
But when I remove the await
, it works but I get a warning on the code "Because this call is not awaited, execution of the current method continues before the call is completed. Consider applying the await operator to the result of the call".
I need to display a message in this catch clause, how do I fix this?
回答1:
Rather than doing the work in the catch
, just set the exception to a local variable. If it's non-null, then you know you need to handle it after the end of the catch
block.
public static async Task Foo()
{
Exception e = null;
try
{
//just something to throw an exception
int a = 0;
int n = 1 / a;
}
catch (Exception ex)
{
e = ex;
}
if (e != null)
await ShowDialog();
}
来源:https://stackoverflow.com/questions/20199410/message-dialog-not-showing-in-catch-clause