【问题标题】:handle system.Format Exception C#处理 system.Format 异常 C#
【发布时间】:2013-08-23 13:56:42
【问题描述】:

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

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;

    }

在这里,尝试捕获块,所有节点都采用 int 值,但是,因为 _fees 采用“0”值。它向我显示格式异常。我只希望我的节点不显示空字符串。我想处理这个异常。这意味着,它不应该在 "this._fees = Convert.ToInt32(getXmlNode("fees", node));" 行抛出异常因为它返回了我想要的 int 值。

我怎样才能做到这一点?

【问题讨论】:

    标签: c# wpf exception-handling formatexception


    【解决方案1】:

    你可以avoidcontrol-flowprogrammingtry/catch机制一般使用TryX方法;在你的情况下,int.TryParse,这样:

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

    【讨论】:

    • 我是 WPF 新手。我应该在哪里写这个?
    【解决方案2】:

    你还没有发布xml,我找不到getXmlNode函数
    但我相信它返回的 XmlNode 具有除 int 以外的其他内容(否则,您将使用 InnerText 属性。

    试试这个:

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

    【讨论】:

      猜你喜欢
      • 2018-03-21
      • 1970-01-01
      • 2012-06-11
      • 2011-04-27
      • 2011-09-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多