我知道有些异常类型无法在 catch 块中捕获,例如StackOverflowException
在 .NET 2.0 中。我想知道哪些其他异常是不可取的,或者与不良做法有关。
我想使用这个异常类型列表的方式是每次Exception
在 catch 块中使用时检查它:
private static readonly Type[] _exceptionsToNotCatch = new Type[] { typeof(StackOverflowException) };
// This should never throw, but should not swallow exceptions that should never be handled.
public void TryPerformOperation()
{
try
{
this.SomeMethodThatMightThrow();
}
catch (Exception ex)
{
if (_exceptionsToNotCatch.Contains(ex.GetType()))
throw;
}
}
编辑
我不认为我提供了一个很好的例子。这是在试图传达一个人的意思时试图让一个例子变得微不足道的问题之一。
我自己从不抛出异常,我总是捕获特定的异常,只捕获异常如下:
try
{
this.SomeMethodThatMightThrow();
}
catch (SomeException ex)
{
// This is safe to ignore.
}
catch (Exception ex)
{
// Could be some kind of system or framework exception, so don't handle.
throw;
}
我的问题更像是一个学术问题。哪些异常只由系统抛出,不应该被捕获?我更担心这样的情况:
try
{
this.SomeMethodThatMightThrow();
}
catch (OutOfMemoryException ex)
{
// I would be crazy to handle this!
// What other exceptions should never be handled?
}
catch (Exception ex)
{
// Could be some kind of system or framework exception, so don't handle.
throw;
}
这个问题的真正灵感来自以下内容: System.Data.EntityUtil.IsCatchableExceptionType(Exception) in System.Data.Entity, Version=3.5.0.0