try-catch的使用

1. 语法:

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();

猜你喜欢

转载自www.cnblogs.com/yanzi8/p/9811869.html