You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

为何这段Fraction类Parse方法代码抛出Length不能小于零的异常?

System.ArgumentOutOfRangeException异常原因分析

异常触发场景

以下代码的Fraction.Parse方法运行时抛出System.ArgumentOutOfRangeException,异常信息为:Message=Length cannot be less than zero. (Parameter 'length')

class Fraction
{
    private double Numerator = 0;
    private double Denominator= 1;

    public static Fraction Parse(string str)
    {
        Fraction newFrac = new Fraction();

        int indexSlash = str.IndexOf("/");
        newFrac.Numerator = int.Parse(str.Substring(0, indexSlash));
        newFrac.Denominator = int.Parse(str.Substring(indexSlash + 1));

        return newFrac;
    }
}

核心原因

  • 输入字符串不含"/"字符:当传入的str中没有"/"时,str.IndexOf("/")会返回-1。
  • Substring方法参数非法:执行str.Substring(0, indexSlash)时,第二个参数length被传入-1,而Substring方法要求length必须≥0,因此直接触发该异常。

补充说明

即使第一个Substring调用未执行到(比如逻辑调整),若indexSlash为-1,indexSlash + 1等于0,此时如果输入字符串为空,str.Substring(0)也会引发异常,但触发当前提示信息的核心原因仍是找不到"/"导致第一个Substring的length参数为负数。

内容的提问来源于stack exchange,提问作者Nacho

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.16 00:30:54