c# 异常处理 try --catch

初学 try---catch 语法

try
{
    可能会出现异常的代码;
    异常出现的那行代码下面的代码全不会执行,直接跳到catch中执行
    ...
    ...
}
//try和catch之间不能有其他的代码
catch
{
    出现异常后要执行的代码;
}

技巧

           Console.WriteLine("你的语文成绩?");
            int chainese = 0;//声明变量再初始化赋值为0,因为在try中声明作用域只能在try中的大括号中有效.
            bool chaineseExecption = true;//这是一个小技巧,异常执行catch中代码并这个赋值变量为false
            //当输入非数字字符串报异常处理办法
            try
            {
                chainese = int.Parse(Console.ReadLine());//接受的是非数字字符串异常
            }
            catch
            {
                Console.WriteLine("你输入的内容不能转换成字符串");
                chaineseExecption = false; //
            }

            if (chaineseExecption == true)//异常不执行的代码
            {
                if (chainese >= 90)
                {
                    Console.WriteLine("语文成绩{0}, 成绩优秀奖励100元RMB");
                }
                else
                {
                    Console.WriteLine("继续努力希望下次你能考出好的成绩");
                }
            }
            Console.ReadKey();