1

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?

Tester
  • 2,887
  • 10
  • 30
  • 60
  • http://stackoverflow.com/questions/8868123/await-in-catch-block this link could be of help. – HappyLee Nov 25 '13 at 17:34
  • Please don't post the same question multiple times. The biggest reason you shouldn't do this is that there is a risk that both your questions will get closed as duplicates of each other. – ZombieSheep Nov 25 '13 at 17:35
  • Also, FYI - Please read the part 'Where can't I use "await"? from http://blogs.msdn.com/b/pfxteam/archive/2012/04/12/10293335.aspx#14 – HappyLee Nov 25 '13 at 17:37
  • Sorry was getting some internet problems, didn't see it posted successfully, which is why I posted another. – Tester Nov 25 '13 at 17:38

1 Answers1

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();
}
Servy
  • 202,030
  • 26
  • 332
  • 449