C# try catch

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# 6的新功能,它影响异常和catch处理程序的匹配方式,允许指定catch除了程序的额外,处理条件。这些条件采用的形式是when关键字布尔表达式

  例如:

catch (OverflowException oe) when (oe.GetType() != typeof(System.FormatException))
{
//处理之前没有捕捉除了FormatException之外的所有异常
Console.WriteLine("FormatException之外的所有异常");
}

  

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