C#中的特定异常和一般异常有什么区别?

时间:2015-04-07 14:32:14

标签: c# exception

我想知道C#中的Specific和General Exception之间的区别。如果有人以一个例子回答我会很有帮助。

1 个答案:

答案 0 :(得分:1)

以下是差异:请参阅示例以获得清晰的理解

示例:

    class Program
   {
    static void Main()
    {
        try
        {
            int[] array = new int[100];
            array[0] = 1;
            array[10] = 2;
            array[200] = 3; // this line will through *IndexOutOfRangeException* Exception

            object o = null;
            o.ToString(); // this line will through *NullReferenceException* Exception
        }
        /* the below catch block(IndexOutOfRangeException class) will only catch *IndexOutOfRangeException* and not *NullReferenceException*
          hence you can say it as Specific Exception as it is catching only a particular exception.
        */
        catch (IndexOutOfRangeException e) 
        {
            Console.WriteLine("Incorrect Index"); // Or any of you Custom error message etc.
        }
        /* the below catch block(Exception class) will catch all the type of exception and hence you can call it as Generic Exception.
        */
        catch (Exception e)
        {
            Console.WriteLine("Opps Something Went Wrong..."); // Or any of you Custom error message etc.
        }

    }
}

特殊例外:正如您在上面的示例中所看到的,IndexOutOfRange只处理一种类型的异常,因此您可以将其视为特定异常。

通用异常:这些异常类可以处理任何类型的异常。因此可以将其称为广义异常。

您可以获得更多信息here。对于Hierarchy of Exceptions,您可以查看here