0

In my app, I don't understand how do handle system.format Exception. 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. 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));" because it's returning int value which I want.

How could I achieve that?

user2622971
  • 605
  • 2
  • 9
  • 19

2 Answers2

5

You can avoid control-flow programming with try/catch mechanisms generally by using TryX methods; in your case, int.TryParse, such that:

int output;
if (int.TryParse(input, out output)) {
  // success
} else {
  // failure
}
Community
  • 1
  • 1
Grant Thomas
  • 42,191
  • 8
  • 81
  • 120
0

you haven't posted the xml, and I can't find the getXmlNode function
but I beleive that it returns XmlNode that have a content other then just int (else, you would use the InnerText property.

do try this:

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