简体   繁体   中英

How to print the exception in Windows Phone?

I am trying to code an app for windows phone 8. I want to print the exception to the screen if I get any. So here is what I am doing:

try
            {
               //The code which I want to handle for exception
            }
            catch (Exception e)
            {
                ErrorStatus.Text = e.Message + "\n\n" + e.Source + "\n\n" + e.StackTrace;
            }

where ErrorStatus is my TextBlock. However, the only line in my catch block is giving me an exception during the runtime. The exception is:

A first chance exception of type 'System.UnauthorizedAccessException' occurred in System.Windows.ni.dll An exception of type 'System.UnauthorizedAccessException' occurred in System.Windows.ni.dll and wasn't handled before a managed/native boundary

Am I doing something wrong syntactically? I am new to C# programming as well as Windows Phone programming.

Edit:

More details of the exception:

System.UnauthorizedAccessException was unhandled by user code
HResult=-2147024891
Message=Invalid cross-thread access.
Source=System.Windows
InnerException: 

You need to show your message from the UI thread: web calls always callback on a background worker thread. So, you need to call the Dispatcher to get this to run on the UI thread.

Also you can just use Exception.ToString() to show the message content as a string. This has the advantage of also showing any nested exceptions inside the one you're handling.

As a temporary measure try:

catch (Exception e)
{
    Deployment.Current.Dispatcher.BeginInvoke(() =>
    {
        ErrorStatus.Text = e.ToString();
    }
}

More permanently you should either fix the issue or log it to a file so you aren't catching exceptions which are masking bugs in your code.

This is the best way to print out your exception message so that you may know where the problem is:

try{}
catch(Exception ex)
{
    await new MessageDialog("Error message:\n\n" + ex.message).ShowAsync();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM