码迷,mamicode.com
首页 > Windows程序 > 详细

C# try catch

时间:2017-11-16 21:58:17      阅读:268      评论:0      收藏:0      [点我收藏+]

标签:程序   for   gen   实验   定义   space   image   static   lin   

1、代码放到try快中(try是c#的关键字)。代码运行是,会尝试执行try块内部的语句,如果么有语句发生异常,这些语句将顺序执行下去。直到全部都完成,但是一旦出现异常就跳出try块,执行catch块中的内容。2、try块需要一个或者多个catch块程序捕捉并处理特定类型的异常。

  实验步骤:首先通过控制台程序输入一串字符,使用Console.readLine();获取一串字符串数据。

       然后使用后int.parse(string s);这个函数将字符串转换为int型数据。

       通过查看int.parse(string s);函数定义可以知道他又如下异常。

      

 // 异常:
        //   T:System.ArgumentNullException:
        //     s 为 null。
        //
        //   T:System.FormatException:
        //     s 的格式不正确。
        //
        //   T:System.OverflowException:
        //     s 表示一个小于 System.Int32.MinValue 或大于 System.Int32.MaxValue 的数字。

      实现代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace tesetData
{
    class Program
    {
       

       
        static void Main(string[] args)
        {
            //try catch的使用 
            string readString = Console.ReadLine();
            int readValue;
            try
            {
                readValue = int.Parse(readString);
                Console.WriteLine(readValue);
            }
            catch (OverflowException)
            {
                Console.WriteLine("err:转化的不是一个int型数据");
            }
            catch (FormatException)
            {
                Console.WriteLine("err:格式错误");
            }
            catch (ArgumentNullException)
            {
                Console.WriteLine("err:null");
            }
            Console.ReadLine();
        }
    }
}

      技术分享技术分享

 

 技术分享

 

C# try catch

标签:程序   for   gen   实验   定义   space   image   static   lin   

原文地址:http://www.cnblogs.com/hjxzjp/p/7846318.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!