当前位置:首页 > 读后感 > [try-catch的使用(简单用法)]try catch用法
 

[try-catch的使用(简单用法)]try catch用法

发布时间:2019-06-29 05:35:38 影响了:

c#中异常捕获

语法:

try

{

有可能出现错误的代码写在这里

}

catch

{

出错后的处理

}

如果try中的代码没有出错,则程序正常运行try中的内容后,不会执行catch中的内容,

如果try中的代码一但出错,程序立即跳入catch中去执行代码,那么try中出错代码后的所有代码就不再执行了.

try

{

Console.WriteLine("请输入你的语文成绩");

int chineseScore=Convert.ToInt32(Console.ReadLine());

Console.WriteLine("请输入你的数学成绩");

int mathScore=Convert.ToInt32(Console.ReadLine());

Console.WriteLine("你的总成绩是:{0}你的平均成绩是:{1}",chineseScore+mathScore,(chineseScore+mathScore)/2);

}

catch

{

Console.WriteLine("你输入的有误,请再次运行后输入");

}

Console.ReadKey();

例2:

try

{

Console.WriteLine("请输入你的姓名");

string name=Console.ReadLine();

Console.WriteLine("请输入语文成绩");

int chineseScore=Convert.ToInt32(Console.ReadLine());

Console.WriteLine("请输入数学成绩");

int mathScore=Convert.ToInt32(Console.ReadLine());

Console.WriteLine("请输入英语成绩");

int englishScore=Convert.ToInt32(Console.ReadLine());

Console.WriteLine("{0}你的总分为{1}分,平均为{2}分",name,chineseScore+mathScore+englishScore,(chineseScore+mathScore+englishScore)/3);

}

catch

{

Console.WriteLine("你输入的有误,请重新运行本程序");

}

Console.ReadKey();

例3.1,

try

{

Console.WriteLine("请输入你要计算的天数");

int days=Convert.ToInt32(Console.ReadLine());

int week=days/7;

int number=days%7;

Console.WriteLine("{0}是{1}周,零{2}天",days,week,number);

}

catch

{

Console.WriteLine("你输入有误,请重新启动程序再输一次");

}

Console.ReadKey();

例3.2:

try

{

Console.WriteLine("请输入你要计算的天数");

int days=Convert.ToInt32(Console.ReadLine());

int month=days/30;

int week=(days-month*30)/7;

int dayNumber=days-month*30-week*7;

Console.WriteLine("{0}天中有{1}月,{2}周,{3}天.",days,month,week,dayNumber);

}

catch

{

Console.WriteLine("你输入的有误,请重新输入一次");

}

Console.ReadKey();

上题也可以这样书写代码:

try

{

Console.WriteLine("请输入你要计算的天数");

int days=Convert.ToInt32(Console.ReadLine());

int month=days/30;

int mot=days%30;//除去上面一个月30天的天数后还剩多少天.

int week=mot/7;//看看剩下的天数中有多少个周。

int dayNumber=mot%7;//除去上面一个周7天的天数后还剩多少天.

Console.WriteLine("{0}天中有{1}月,{2}周,{3}天",days,month,week,dayNumber);

}

catch

{

Console.WriteLine("你输入的有误,请重新输入");

}

Console.ReadKey();

例3.3

try

{

Console.WriteLine("请输入你要转换的秒数");

int seconds=Convert.ToInt32(Console.ReadLine());

int days=seconds/(3600*24);//总秒数除以1天的秒数就得出有多少天数了

int mod=seconds%(3600*24);//看看除去上面秒数还剩下多少秒

int hours=mod/3600;//用上面一步剩下的秒除以1小时的秒数就得出有多少小时了

mod=mod%3600;//看看除去上面一步秒数还剩下多少秒

int min=mod/60;//用上面一步剩下的秒数除以1分钟的秒数就得出有多少分钟了

int second=mod%60;看看除去上面一步秒数还剩下多少秒

Console.WriteLine("{0}中共有{1}天,{2}小时,{3}分,{4}秒",seconds,days,hour,min,second);

}

catch

{

Console.WriteLine("你输入有误,请重新输入");

}

Console.ReadKey();


猜你想看
相关文章

Copyright © 2008 - 2022 版权所有 职场范文网

工业和信息化部 备案号:沪ICP备18009755号-3