Message dialog not showing in catch clause [duplicate]

倖福魔咒の 提交于 2019-12-11 07:43:18

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!