C#中 try catch的作用

例如:想执行 int score=Conver.ToInt32(Console.ReadLine());但是用户不一定会直接输入int类型,所以为了避免用户输入错误。就有了try catch。

下面有段代码可以试着执行一下,以便更好地理解。

try

{

  int score=Conver.ToInt32(Console.ReadLine());

  Console.WriteLine("in try");

}

catch

{

   Console.WriteLine("in catch");

}

 Console.WriteLine("over");

 Console.ReadKey();

运行结果说明:如果try中的代码没有出异常,则不会执行catch中的代码。如果try中的代码出现异常,则立即执行catch中的代码。

 

posted @ 2016-07-13 08:05  CCT不加V  阅读(1413)  评论(0编辑  收藏  举报