TheRookierLearner
TheRookierLearner

Reputation: 4163

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: 

Upvotes: 1

Views: 807

Answers (2)

Timothy Macharia
Timothy Macharia

Reputation: 2926

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();
}

Upvotes: 0

Paul Annetts
Paul Annetts

Reputation: 9604

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.

Upvotes: 3

Related Questions