如何处理“溢出”错误

来源:互联网 发布:最赚钱的软件 编辑:程序博客网 时间:2024/05/01 22:59

///如何处理“溢出”错误
namespace CSharp开发经验技巧宝典
{
    class _046
    {
        static void Main(String[] args)
        {
            int x = int.MinValue;
            int y = int.MaxValue;

            int z = 0;
            try
            {
                //z = unchecked((int)(x * y));//这个是在未检查的上下文中,算法溢出被忽略并且结果被截断
                //z = checked((int)(x * y));//这个表示在已检查的上下文中,算法溢出则抛出一个      

                                                         //OverflowException异常
            }
            catch (System.OverflowException ex)
            {
                Console.WriteLine(ex.Message);
            }
            Console.WriteLine(x + " + " + y + " = " + z);
            Console.ReadLine();
        }
    }
}

原创粉丝点击