具有特定异常类的主要优点是什么,因为我们可以在System.Exception类中拥有所有异常。 为什么要使用特定的错误处理类?
答案 0 :(得分:1)
异常处理程序在逐个类的基础上工作。如果您只有一个例外类,则无法执行此操作:
try
{
//Do something that might raise different types of exceptions
}
catch(ArgumentException e1) //Catch any exception that is an ArgumentException or one its derived types
{
//Do something to handle the invalid argument
}
catch(NetworkException e2) //Catch any exception that is a NetworkException or one of its derived types
{
//Do something to handle the issue with the network
}
catch(Exception e3)
{
//Do something to log the unexpected exception
throw;
}
请注意you should not catch the base exception除非您正在做的唯一事情就是记录并重新抛出。