C# 异常

93 阅读1分钟

异常

异常与异常处理语句包括三种形式,即 try catch、try finally、try catch finally。

在上述三种异常处理的形式中所用到关键字其含义如下:

  • try:用于检查发生的异常,并帮助发送任何可能的异常。 
  • catch:以控制权更大的方式处理错误,可以有多个 catch 子句。 
  • finally:无论是否引发了异常,finally 的代码块都将被执行。 
//从控制台输入 5 个数存入整数数组中

class Program
{
    static void Main(string[] args)
    {
        //定义存放5个整数的数组
        int[] a = new int[5];
        try
        {
            for(int i = 0; i < a.Length; i++)
            {
                a[i] = int.Parse(Console.ReadLine());
            }
            for(int i = 0; i < a.Length; i++)
            {
                Console.Write(a[i] + " ");
            }
        }
        catch(FormatException f)
        {
            Console.WriteLine("当参数格式不符合调用的方法的参数规范时引发的异常!");
        }
        catch(OverflowException o)
        {
            Console.WriteLine("变量值溢出和方法值溢出");
        }
        catch(IndexOutOfRangeException r)
        {
            Console.WriteLine("处理当方法指向超出范围的数组索引时生成的错误");
        }
        
        // 无论 try是否异常 都会执行
        // 通常在 finally 中编写的代码是关闭流、关闭数据库连接等操作,以免造成资源的浪费。
        finally
        {
            Console.WriteLine("无论是否异常 都会执行");
        }

    }
}
自定义异常
声明异常的语句如下
class 异常类名 :Exception{}

抛出自己的异常,语句如下
throw( 异常类名 );