我想知道C#中的Specific和General Exception之间的区别。如果有人以一个例子回答我会很有帮助。
答案 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只处理一种类型的异常,因此您可以将其视为特定异常。
通用异常:这些异常类可以处理任何类型的异常。因此可以将其称为广义异常。