用正则表达式 ^[1-9]表示一个不含0的正整数。输入大于等于2^31=2147483648时(比如输入254524254205495044),就会报错,然后程序强制终止,因为超过了32位符号型的最大取值范围了。请问应该如何手动判断这个错误?(也就是程序提示一条出错消息,而不是系统报错然后强制终止程序)。

解决方案 »

  1.   

    try
    {
    int n = int.Parse("254524254205495044");
    }
    catch (OverflowException)
    {
    Console.WriteLine("too big");
    return;
    }
      

  2.   

    或者
    int n;
    if (!int.TryParse("254524254205495044", out n))
    {
    Console.WriteLine("too big");
    return;
    }
      

  3.   

    试过了,不行else if (Regex.IsMatch(command, @"^n[0-9]"))
                    {
                        int seed = Convert.ToInt32(command.Substring(1));
                        puzzle1.ShufflePuzzle(i_row, i_column, seed, puzzle_array);//change column
                        puzzle1.PrintPuzzle(i_row, i_column, puzzle_array);//print puzzle
                    }代码如上,貌似IsMatch的时候就出错了。