C# 抛出异常并用相同的方法捕获为什么不好?
C# Throw Exception and catch in the same method why it's bad?
对一种实现进行一些讨论:
// Pseudocode
accessor type GetValue()
{
try
{
do some action with possible throw exception1
do some action with possible throw exception2
return value;
}
catch (Exception ex)
{
value = default;
throw Wraped in Meaningfull Exception ex
}
}
有人可以解释为什么它可能是一个糟糕的设计,像那样使用 try
-catch
(以相同的方法抛出和捕获)来安全地执行某些操作并聚合不同类型的类似的例外?
不是重抛
throw new WrapedException("MyNewMessage", ex);
这是错误的,但捕获了 所有 异常
catch (Exception ex) {
...
}
是一个糟糕的设计:它掩盖了潜在的危险行为。让我们看看为什么。假设我们这样使用 GetValue()
:
try {
someValue = GetValue();
}
catch (WrapedException) {
// We failed to obtain someValue;
// The reason - WrapedException - is innocent
// Let's use default value then
someValue = defaultSomeValue;
}
而实际图片是
public GetValue() {
try {
do some action with possible throw exception1
// Catastrophy here: AccessViolationException! System is in ruins!
do some action with possible throw exception2
return value;
}
catch (Exception ex) { // AccessViolationException will be caught...
// ...and the disaster will have been masked as being just WrapedException
throw new WrapedException("MyNewMessage", ex);
}
}
如果您只捕获预期的异常类型,您的设计就没问题:
public GetValue() {
try {
do some action with possible throw exception1
do some action with possible throw exception2
return value;
}
catch (FileNotFound ex) {
// File not found, nothing special in the context of the routine
throw new WrapedException("File not found and we can't load the CCalue", ex);
}
}
对一种实现进行一些讨论:
// Pseudocode
accessor type GetValue()
{
try
{
do some action with possible throw exception1
do some action with possible throw exception2
return value;
}
catch (Exception ex)
{
value = default;
throw Wraped in Meaningfull Exception ex
}
}
有人可以解释为什么它可能是一个糟糕的设计,像那样使用 try
-catch
(以相同的方法抛出和捕获)来安全地执行某些操作并聚合不同类型的类似的例外?
不是重抛
throw new WrapedException("MyNewMessage", ex);
这是错误的,但捕获了 所有 异常
catch (Exception ex) {
...
}
是一个糟糕的设计:它掩盖了潜在的危险行为。让我们看看为什么。假设我们这样使用 GetValue()
:
try {
someValue = GetValue();
}
catch (WrapedException) {
// We failed to obtain someValue;
// The reason - WrapedException - is innocent
// Let's use default value then
someValue = defaultSomeValue;
}
而实际图片是
public GetValue() {
try {
do some action with possible throw exception1
// Catastrophy here: AccessViolationException! System is in ruins!
do some action with possible throw exception2
return value;
}
catch (Exception ex) { // AccessViolationException will be caught...
// ...and the disaster will have been masked as being just WrapedException
throw new WrapedException("MyNewMessage", ex);
}
}
如果您只捕获预期的异常类型,您的设计就没问题:
public GetValue() {
try {
do some action with possible throw exception1
do some action with possible throw exception2
return value;
}
catch (FileNotFound ex) {
// File not found, nothing special in the context of the routine
throw new WrapedException("File not found and we can't load the CCalue", ex);
}
}