Cha*_*adD 8 .net exception-handling
为什么抛出此异常更可取
Throw New DivideByZeroException("You can't divide by zero")
Run Code Online (Sandbox Code Playgroud)
在这个一般的一个:
Throw New Exception("You can't divide by zero")
Run Code Online (Sandbox Code Playgroud)
在这个特定的例子中获得了什么好处?消息已经告诉了所有.从基础Exception类继承的标准子类是否有不同的基础方法?我没有看到一个案例,但我必须承认我倾向于抛出基础异常.
Ron*_*lic 20
异常的类型允许异常处理程序对其进行过滤.如果您抛出的只是类型的异常,Exception处理程序将如何知道要捕获的异常以及允许在调用堆栈中传播的异常?
例如,如果你总是抛出Exception:
void Foo(string item) {
try {
if (Bar(item)) {
Console.WriteLine("BAR!");
}
} catch (Exception e) {
Console.WriteLine("Something bad?");
}
}
bool Bar(string item) {
if (item == null) {
throw new Exception("Argument is null!");
}
return Int32.Parse(item) != 0;
}
Run Code Online (Sandbox Code Playgroud)
调用者如何Foo知道是否发生了空异常或者Int32.Parse()失败了?它必须检查抛出的异常的类型(或做一些讨厌的字符串比较).
如果你得到一个ThreadAbortException或OutOfMemoryException哪个可能出现在你不希望异常的地方,那就更令人担忧了.在这些情况下,如果捕获代码仅捕获Exception,则可能会掩盖这些(重要)异常并导致程序(或系统)状态受损.
示例代码应为:
void Foo(string item) {
try {
if (Bar(item)) {
Console.WriteLine("BAR!");
}
} catch (ArgumentNullException ae) {
Console.WriteLine("Null strings cannot be passed!");
} catch (FormatException fe) {
Console.WriteLine("Please enter a valid integer!");
}
}
bool Bar(string item) {
if (item == null) {
throw new ArgumentNullException("item");
}
return Int32.Parse(item) != 0;
}
Run Code Online (Sandbox Code Playgroud)
因为您可以使用多个catch语句并以不同方式处理不同的错误.
例如,DivideByZero异常可能会提示用户更正条目,而FileNotFound异常可能会提醒用户程序无法继续并关闭程序.
这里有一篇很好的深入文章回答这个问题:http://blogs.msdn.com/b/dotnet/archive/2009/02/19/why-catch-exception-empty-catch-is-bad.aspx
您可以捕获多种类型的异常,而不是基于沿错误流发送的文本进行过滤.每个人都可能有一种非常具体的方式来执行恢复.文本只是为用户或调试器提供一些反馈,但程序关心异常类型.出于同样的原因,用户创建的类存在多态性,但存在例外情况.
为不同的异常类型包含多个catch语句要比解析消息文本以了解正确处理问题需要做什么要容易得多.