2013-08-23 44 views
0

在我的应用程序中,我不明白如何处理system.format异常。请参见下面的代码句柄system.format异常C#

public Harvest_Project(XmlNode node) 
    { 
     this._node = node; 
     this._name = node.SelectSingleNode("name").InnerText; 

     this._created_at = storeTime(node.SelectSingleNode("created-at").InnerText); 
     this._updated_at = storeTime(node.SelectSingleNode("updated-at").InnerText); 
     this._over_budget_notified_at = storeTime(node.SelectSingleNode("over-budget-notified-at").InnerText); 
     this._latest_record_at = storeTime(node.SelectSingleNode("hint-latest-record-at").InnerText); 
     this._earliest_record_at = storeTime(node.SelectSingleNode("hint-earliest-record-at").InnerText); 

     this._billable = bool.Parse(node.SelectSingleNode("billable").InnerText); 

     try 
     { 
       this._id = Convert.ToInt32(node.SelectSingleNode("id").InnerText); 
       this._client_id = Convert.ToInt32(node.SelectSingleNode("client-id").InnerText); 
       this._budget = float.Parse(node.SelectSingleNode("budget").InnerText); 
       this._fees = Convert.ToInt32(getXmlNode("fees", node)); 

     } 
     catch (FormatException e) 
     { 

      Console.WriteLine(); 
     } 
     catch (OverflowException e) 
     { 
      Console.WriteLine("The number cannot fit in an Int32."); 
     } 

     this._code = node.SelectSingleNode("code").InnerText; 
     this._notes = node.SelectSingleNode("notes").InnerText; 

    } 

在这里,尝试和catch块,所有的节点需要int类型,但是,作为_fees以“0”值。它显示我格式异常。我只想让我的节点不显示空字符串。我想处理这个异常。这意味着,它不应该抛出异常在“this._fees = Convert.ToInt32(getXmlNode(”fees“,node));”因为它返回我想要的int值。

我怎么能做到这一点?

回答

5

您可以avoidcontrol-flowprogrammingtry/catch机制一般通过使用TryX方法;你的情况,int.TryParse,使得:

int output; 
if (int.TryParse(input, out output)) { 
    // success 
} else { 
    // failure 
} 
+2

[文档在这里(http://msdn.microsoft.com/en-us/library/f02979c7.aspx) – tnw

+0

我是WPF的新手,我应该在哪写这篇文章? – user2622971

0

你还没有发布的XML,我无法找到getXmlNode功能
但我beleive,它返回的XmlNode有一个其他内容则正好诠释(否则,你会使用InnerText属性

就试试这个:

XmlNode fees = getXmlNode(...) 
var curr = fees.FirstChild; 
int _fees = 0; 
while (curr != null) { 
    _fees += (Convert.ToInt32(curr.InnerText); 
    curr = curr.NextSibling(); 
}