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

C#代码无法捕获IndexOutOfRangeException问题求助

问题分析与解决

你的IndexOutOfRangeException捕获代码完全没生效,核心原因有两个:

  • int.Parse()方法永远不会抛出索引越界异常,它只会在输入不是有效整数、数值溢出、输入为空时抛出对应异常,所以你写的catch (IndexOutOfRangeException)分支永远走不到。
  • 真正触发索引越界异常的代码是最后一行return myBoard.theGrid[currentRow, currentColumn];,这行代码不在任何try代码块范围内,所以异常直接向外抛出,根本没被你的捕获逻辑处理。

正确的解决方式

更合理的做法是先验证输入的数值范围,再去访问数组,异常应该用来处理意外情况,用户输入的范围验证属于业务逻辑判断,不该依赖异常捕获。

修改后的代码示例:

class Program
{
    static Board myBoard = new Board(8);
    // 定义边界常量,避免硬编码
    private const int GridSize = 8;

    public static Cell setCurrentCell()
    {
        int currentRow, currentColumn;
        
        Console.Write("Enter a current row number: ");
        while (true)
        {
            try
            {
                currentRow = int.Parse(Console.ReadLine());
                // 解析成功后立即验证范围
                if (currentRow >= 0 && currentRow < GridSize)
                {
                    break;
                }
                else
                {
                    Console.Write($"Input was out of range, try a number between 0 and {GridSize-1}. Please try again: ");
                }
            }
            catch (FormatException)
            {
                Console.Write("Input has to be a number, try again: ");
            }
            // 不再需要捕获IndexOutOfRangeException,提前验证已避免异常
        }

        Console.Write("Enter the current column number: ");
        while (true)
        {
            try
            {
                currentColumn = int.Parse(Console.ReadLine());
                if (currentColumn >= 0 && currentColumn < GridSize)
                {
                    break;
                }
                else
                {
                    Console.Write($"Input was out of range, try a number between 0 and {GridSize-1}. Please try again: ");
                }
            }
            catch (FormatException)
            {
                Console.Write("Input has to be a number, try again: ");
            }
        }
        return myBoard.theGrid[currentRow, currentColumn];
    }
}

额外优化建议

  • 把重复的输入验证逻辑封装成单独方法,避免代码冗余,比如写一个int GetValidCoordinate(string prompt)方法统一处理行和列的输入。
  • 用int.TryParse()替代int.Parse(),无需依赖异常捕获处理格式错误,代码更简洁:
// 示例:封装的验证方法
private static int GetValidCoordinate(string prompt)
{
    while (true)
    {
        Console.Write(prompt);
        if (int.TryParse(Console.ReadLine(), out int value) && value >= 0 && value < GridSize)
        {
            return value;
        }
        Console.Write($"Invalid input, please enter a number between 0 and {GridSize-1}: ");
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 07:05:18