简体   繁体   English

如何捕获system.xml.xmlexception

[英]How to catch system.xml.xmlexception

I published a small free App for Windows Phone 8 Smartphones (to get to know C# - so I am a beginner in programming). 我发布了一个用于Windows Phone 8智能手机的小型免费应用程序(了解C#,因此我是编程的初学者)。 A lot of my users seem pretty happy with the functionality but some of them seem to keep getting random crashes (for example in Canada: http://www.windowsphone.com/en-ca/store/app/picture-of-the-day/fc977a34-c09d-4c70-8a7b-66b6f09ab7f0 ) I never experienced such crashes on my test devices and tried to get rid of them by adding more try-catch statements - but without success. 我的许多用户似乎对该功能感到非常满意,但其中一些用户似乎一直在随机崩溃(例如在加拿大: http//www.windowsphone.com/zh-cn/store/app/picture-of-the -day / fc977a34-c09d-4c70-8a7b-66b6f09ab7f0 )我从未在测试设备上遇到过此类崩溃,并试图通过添加更多try-catch语句来摆脱它们,但没有成功。

The crash report states the following: 崩溃报告指出以下内容:

Frame Image Function Offset        
0 system_xml_ni System.Xml.XmlTextReaderImpl.Throw 0x00000036    
1 system_xml_ni System.Xml.XmlTextReaderImpl.ParseDocumentContent 0x00000438    
2 system_xml_ni System.Xml.XmlTextReaderImpl.Read 0x00000036    
3 system_xml_linq_ni System.Xml.Linq.XDeclaration..ctor 0x00000072    
4 system_xml_linq_ni System.Xml.Linq.XDocument.Load 0x0000010a    
5 system_xml_linq_ni System.Xml.Linq.XDocument.Load 0x00000042    
6 system_xml_linq_ni System.Xml.Linq.XDocument.Load 0x00000006    
7 phoneapp1_ni PhoneApp1.MainPage+__c__DisplayClassb._doLoadURL_b__6 0x00000040    
8 system_net_ni System.Net.WebClient.OnOpenReadCompleted 0x00000010    
9 system_net_ni System.Net.WebClient.OpenReadOperationCompleted 0x00000034`

The actual code that I think is responsible: 我认为负责的实际代码:

try 
{
    WebClient client = new WebClient();
    client.OpenReadAsync(new Uri(Url, UriKind.Absolute));
    client.OpenReadCompleted += (sender, e) =>
    {
        if (e.Error != null)
        {
            return;
        }
        else
        {
            System.Xml.Linq.XDocument xmlDoc = XDocument.Load(e.Result);
            IEnumerable<string> strTestURL = from node in xmlDoc.Descendants("url") select node.Value;
            IEnumerable<string> strTestDescription = from node in xmlDoc.Descendants("copyright") select node.Value;
            IEnumerable<string> strTestDate = from node in xmlDoc.Descendants("enddate") select node.Value;
            string strURL = "http://www.bing.com" + strTestURL.First();
            strURL = strURL.Replace("1366x768", "800x480");
            Global.URL1 = strURL;
            Global.URLs[i] = strURL;
            Global.Descriptions[i] = strTestDescription.First();
            Uri Uri = new Uri(Global.URLs[i], UriKind.Absolute);
            Imageallgemein.Source = new BitmapImage(Uri);
            Imageallgemein.Tap += new EventHandler<System.Windows.Input.GestureEventArgs>(onImageTap);
            Imageallgemein.Hold += new EventHandler<System.Windows.Input.GestureEventArgs>(onImageTap);
            Description.Text = Global.Descriptions[i];
            string Year = strTestDate.First().Substring(0, 4);
            string Month = strTestDate.First().Substring(4, 2);
            string Day = strTestDate.First().Substring(6, 2);
            Date.Text = Day + "." + Month + "." + Year;
        }
    };
}
catch
{
    MessageBox.Show(AppResources.Abort, AppResources.msgBoxUrlLoadError, MessageBoxButton.OK);
}

try-catch seems to have no effect and I hope someone can solve this for me. try-catch似乎没有任何效果,我希望有人可以为我解决这个问题。

There must be some problem with the XML provided by e.Result . e.Result提供的XML必须存在一些问题。 Details about this might be in the XmlException message but you only included part of the stack trace. 有关此问题的详细信息可能在XmlException消息中,但是您只包括了堆栈跟踪的一部分。

You will have to figure out what the problem is in the first place and you will probably have to add some logging of what happens BEFORE you call XDocument.Load if you are unable to reproduce the problem on your own system. 您首先必须弄清楚问题出在哪里,并且如果您无法在自己的系统上重现该问题,则可能必须在调用XDocument.Load之前添加一些记录。

You can also add an exception handler but that does not fix the problem but makes your app more robust and allows it to provide a slightly better user interface if something unexpected happens. 您还可以添加一个异常处理程序,但是它不能解决问题,但是可以使您的应用程序更加健壮,并允许它在出现意外情况时提供更好的用户界面。 What you have done is adding an exception handler around the calls to the WebClient methods but you are not catching exceptions thrown by the handler for client.OpenReadCompleted . 您所做的是在对WebClient方法的调用周围添加了异常处理程序,但是您没有捕获client.OpenReadCompleted的处理程序抛出的异常。 This is an asynchronous callback that will execute on a threadpool thread, and any uncaught exceptions thrown by this thread will terminate your app. 这是一个异步回调,将在线程池线程上执行,该线程引发的任何未捕获的异常都将终止您的应用程序。

You need to handle the exception with code like this: 您需要使用以下代码处理异常:

client.OpenReadCompleted += (sender, e) =>
{
    try
    {
        if (e.Error != null)
        {
            return;
        }
        else
            ....
    }
    catch (Exception ex)
    {
        .... log and report the exception to allow the app to continue
    }
 }

And if you decide to add logging to your app it will be very useful to you if you log the entire text returned by ex.ToString() . 而且,如果您决定将日志记录添加到您的应用程序中,那么如果您记录ex.ToString()返回的整个文本,这对您将非常有用。 This will give you a good textual description of the problem including inner exceptions and full stack traces. 这将为您提供有关问题的良好文字说明,包括内部异常和完整堆栈跟踪。

Normally is good practice to do catch(Exception) , in your case catch(system.xml.XmlException) . 通常,执行catch(Exception)是一个好习惯,在您的情况下,是catch(system.xml.XmlException) However put a try-catch inside your else block because this is an asynchronous event and if occurs some exception inside that exception will be not catched: 但是,将try-catch放入您的else块中,因为这是一个异步事件,如果发生,则该异常内部的某些异常将不会被捕获:

try 
{
    WebClient client = new WebClient();
    client.OpenReadAsync(new Uri(Url, UriKind.Absolute));
    client.OpenReadCompleted += (sender, e) =>
    {
        if (e.Error != null)
        {
            return;
        }
        else
        {
           try
           {
              System.Xml.Linq.XDocument xmlDoc = XDocument.Load(e.Result);
              IEnumerable<string> strTestURL = from node in xmlDoc.Descendants("url") select node.Value;
              IEnumerable<string> strTestDescription = from node in xmlDoc.Descendants("copyright") select node.Value;
              IEnumerable<string> strTestDate = from node in xmlDoc.Descendants("enddate") select node.Value;
              string strURL = "http://www.bing.com" + strTestURL.First();
              strURL = strURL.Replace("1366x768", "800x480");
              Global.URL1 = strURL;
              Global.URLs[i] = strURL;
              Global.Descriptions[i] = strTestDescription.First();
              Uri Uri = new Uri(Global.URLs[i], UriKind.Absolute);
              Imageallgemein.Source = new BitmapImage(Uri);
              Imageallgemein.Tap += new EventHandler<System.Windows.Input.GestureEventArgs>(onImageTap);
              Imageallgemein.Hold += new EventHandler<System.Windows.Input.GestureEventArgs>(onImageTap);
              Description.Text = Global.Descriptions[i];
              string Year = strTestDate.First().Substring(0, 4);
              string Month = strTestDate.First().Substring(4, 2);
              string Day = strTestDate.First().Substring(6, 2);
              Date.Text = Day + "." + Month + "." + Year;
           }
           catch (XmlException)
           {
                MessageBox.Show(AppResources.Abort, AppResources.msgBoxUrlLoadError, MessageBoxButton.OK);
           }
        }
    };
}
catch (Exception)
{
    MessageBox.Show(AppResources.Abort, AppResources.msgBoxUrlLoadError, MessageBoxButton.OK);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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