zoukankan      html  css  js  c++  java
  • 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之外的所有异常");
    }

      

  • 相关阅读:
    2017ICPC南宁补题
    H. The Game of Life
    I
    Twice Equation
    (贪心+队列)String
    Marcin and Training Camp
    莫比乌斯函数模版
    HDU-1695 莫比乌斯反演
    Steps to One DP+莫比乌斯反演
    Educational Codeforces Round 62 (Rated for Div. 2)
  • 原文地址:https://www.cnblogs.com/hjxzjp/p/7846318.html
Copyright © 2011-2022 走看看