[黑马程序员]_简单的try catch用法和几个小例题

来源:互联网 发布:云数据库 免费 编辑:程序博客网 时间:2024/04/30 00:37

try-catch 语句由一个 try 块后跟一个或多个 catch 子句构成,这些子句指定不同的异常处理程序。try 块包含可能导致异常的保护代码,catch 子句包含仅在屏幕上显示消息的异常处理程序。如果try中代码没有出错,则程序正常运行try中的代码,不会执行catch中的内容,如果try中的代码有误,程序立即跳入catch中去执行代码,那么try中的出错代码后面的代码不再执行。

例题1、让学生输入其姓名和语文、数学、英语成绩,编程求总分和平均分,并在屏幕上显示:xx你的总分数为xx分,平均为xx分。

try            {                Console.WriteLine("请输入你的姓名?");                string name = Console.ReadLine();                Console.WriteLine("请输入你的语文成绩?");                int chinese = Convert.ToInt32(Console.ReadLine());                Console.WriteLine("请输入你的数学成绩?");                int math = Convert.ToInt32(Console.ReadLine());                Console.WriteLine("请输入你的英语成绩?");                int english = Convert.ToInt32(Console.ReadLine());                Console.WriteLine("{0}的三科成绩总分数为{1}分,平均分为{2}分",                    name, chinese + math + english, (chinese + math + english) / 3);            }            catch            {                Console.WriteLine("你输入的数据有误!");            }            Console.ReadKey();

例题2、编程实现计算几天(如46天)是几月几周几天,设定一个月为30天
Console.WriteLine("请输入你要计算的天数?");            int days = Convert.ToInt32(Console.ReadLine());            int month = days / 30;            int mod = days % 30;  //days中的天数除去月份所占用的天数,还剩下多少天。            int week = mod / 7;            int day = mod % 7;  //int day = days - month * 30 - week * 7;            Console.WriteLine("{0}天中共有{1}月{2}周零{3}天",days,month,week,day);            Console.ReadKey();

例题3、编程实现XX秒是几天几小时几分钟几秒?
Console.WriteLine("请输入你要转换的秒数?");            int seconds = Convert.ToInt32(Console.ReadLine());            int days = seconds / (60 * 60 * 24);            int mod = seconds % (60 * 60 * 24);  //出去上面的天数还剩下多少秒            int hour = mod / (60 * 60);  //剩余的秒数中还剩下多少小时            mod = mod % (60 * 60);  //剩余的秒数中除去上面的小时还剩下多少秒            int min = mod / 60;  //剩余的秒数中还有几分钟            int second = mod % 60;  //剩余多少秒            Console.WriteLine("{0}秒中共包含{1}天{2}小时{3}分钟{4}秒",                seconds, days, hour, min, second);            Console.ReadKey();

原创粉丝点击