首页 > 解决方案 > 未处理的异常 System.OverflowException 值对于 Int32 来说太大或太小

问题描述

我在这里有这段C#代码,我想要做的是,当我输入一个包含多位数字的数字时,应用程序崩溃并且我希望它不会崩溃但我不知道该怎么做,我尝试更改.Parse命令但是确定要改用哪个命令。一个例子是,当我运行应用程序时,我想输入一个数字,564984894897987878并且我希望应用程序不会崩溃,在这种情况下,有人可以帮助我吗?如果您找到解决方案,请在此处发布,包括您的代码和我的代码,谢谢!

        int num;
        Console.Write("Please type your number here:");
        num = Int32.Parse(Console.ReadLine());



        if (num < 0)
            Console.WriteLine("This is a negative number!");

        if (num > 0)
            Console.WriteLine("This number is a positive number");

标签: c#

解决方案


If you want to represent an arbitrarily large integer, you should use BigInteger.

If you use int (aka System.Int32) you'll be limited to a range of -2147483648 to 2147483647 inclusive.

If you use long (aka System.Int64) you'll be limited to a range of -9223372036854775808 to 9223372036854775807 inclusive.

Now it could be that long is fine for you here - but a user would still be able to crash your app, or at least make it not work "as expected", pretty easily. With BigInteger you should be fine for any integer value that your computer has enough memory to store.

Your code can be converted almost trivially to use BigInteger - just use BigInteger.Parse instead of Int32.Parse, and then compare with BigInteger.Zero. To improve the code further, beyond just handling large integers, you could use BigInteger.TryParse to handle invalid inputs by gracefully reporting those to the user instead of crashing with a FormatException.


推荐阅读