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




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

c#中异常捕获

语法:

 

try

{

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

}

catch

{

出错后的处理

}

 

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

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

 


 

例1:

try

{

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

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

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

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

Console.WriteLine("你的总成绩是:{0}\n你的平均成绩是:{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();


  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值