[英]handle system.Format Exception C#
In my app, I don't understand how do handle system.format Exception. 在我的应用程序中,我不了解如何处理system.format异常。 See below code 见下面的代码
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;
}
Here in, try and catch blocks, all the nodes takes int values but, as _fees takes "0" value. 在这里,try and catch块中,所有节点都采用int值,但是_fees则采用“ 0”值。 It's showing me format exception. 它向我显示格式异常。 I just want my nodes doesn't show empty string. 我只希望我的节点不显示空字符串。 I want to handle this exception. 我想处理这个异常。 That means, it should not throw exception at line "this._fees = Convert.ToInt32(getXmlNode("fees", node));" 这意味着,它不应在“ this._fees = Convert.ToInt32(getXmlNode(“ fees”,node));;“行上引发异常。 because it's returning int value which I want. 因为它正在返回我想要的int值。
How could I achieve that? 我该如何实现?
You can avoid control-flow programming with try/catch mechanisms generally by using TryX
methods; 通常,可以通过使用TryX
方法来避免使用try / catch机制进行控制流 编程 。 in your case, int.TryParse
, such that: 在您的情况下,为int.TryParse
,这样:
int output;
if (int.TryParse(input, out output)) {
// success
} else {
// failure
}
you haven't posted the xml, and I can't find the getXmlNode function 您尚未发布xml,并且找不到getXmlNode函数
but I beleive that it returns XmlNode that have a content other then just int (else, you would use the InnerText property. 但我相信它返回的XmlNode的内容除了int之外(否则,您将使用InnerText属性。
do try this: 尝试这样做:
XmlNode fees = getXmlNode(...)
var curr = fees.FirstChild;
int _fees = 0;
while (curr != null) {
_fees += (Convert.ToInt32(curr.InnerText);
curr = curr.NextSibling();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.