首页 > 其他 > 详细

黑马程序员_try-catch(异常)

时间:2014-04-02 16:38:29      阅读:451      评论:0      收藏:0      [点我收藏+]
bubuko.com,布布扣
namespace _24.try_catch
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("请输入你的分数");
            try//try中写入容易出错的代码。如果不写try-cathc语句,那么运行程序时,在控制台输入字符串,那么程序报错。
            {
                int score = Convert.ToInt32(Console.ReadLine());
                Console.WriteLine("你输入了一个正确的数字");
            }
            catch
            {
                Console.WriteLine("你输入的不是数字");
            }
            Console.ReadKey();
        }
    }
}
bubuko.com,布布扣
bubuko.com,布布扣
namespace _6.异常
{
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                Console.WriteLine("Convert之前");
                int a = Convert.ToInt32(Console.ReadLine());
                Console.WriteLine("Convert之后");
            }
            catch (Exception ex)
            {
                Console.WriteLine("输入错误:"+ex.Message+"异常堆栈:"+ex.StackTrace);
            }
            

            try
            {
                Console.WriteLine("请输入你的年龄:");
                int s = Convert.ToInt32(Console.ReadLine());
                string desc = GetAgeDesc(s);
                Console.WriteLine(desc);
            }
            catch (Exception ex)
            {
                Console.WriteLine("数据错误,"+ex.Message);
            }
            
            Console.ReadKey();
        }

        static string GetAgeDesc(int age)
        {
            if (age >= 0 && age <= 3)
            {
                return "婴幼儿";
            }
            else if (age > 3 && age < 18)
            {
                return "青少年";
            }
            else if (age >=18 && age < 60)
            {
                return "成年人";
            }
            else if (age >= 60 && age < 100)
            {
                return "老年人";
            }
            else 
            {
                throw new Exception("自己创建的ex.Message");
            }
        }
    }
}
bubuko.com,布布扣

黑马程序员_try-catch(异常),布布扣,bubuko.com

黑马程序员_try-catch(异常)

原文:http://www.cnblogs.com/zn85194051/p/3640867.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!