从不捕获的例外情况

CSh*_*ldt 4 .net c# exception-handling exception catch-block

我知道有些异常类型无法在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;
    }
}
Run Code Online (Sandbox Code Playgroud)

编辑

我认为我没有提供一个很好的例子.这是试图在传达一个人的意思时试图做出一个小例子的问题之一.

我自己从不抛出异常,并且我总是捕获特定的异常,只捕获Exception如下:

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;
}
Run Code Online (Sandbox Code Playgroud)

我的问题更像是一个学术问题.只有系统抛出哪些异常并且永远不会被捕获?我担心的情况更像这样:

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;
}
Run Code Online (Sandbox Code Playgroud)

这个问题的确受到以下内容的启发:System.Data.Entity中的System.Data.EntityUtil.IsCatchableExceptionType(Exception),版本= 3.5.0.0

小智 14

我想知道哪些其他例外不适合捕获,或者与不良做法有关.

以下是您不应该捕获的所有异常的列表:

  1. 您不知道如何处理的任何异常

这是异常处理的最佳实践:

如果您不知道如何处理异常,请不要抓住它.

这可能听起来很讽刺,但它们都是正确的,而这就是你需要知道的.

  • @patxy:当然,你刚刚抓到的那个例外你打算做什么? (2认同)
  • 这并不总是你想要的.例如,如果IDE插件提供了语法高亮显示,则编辑器可以捕获突出显示器抛出的"大多数"异常,并通过在会话的其余部分禁用语法突出显示来进行响应.重要的问题是在这种情况下不应该抓住哪些例外,这正是OP提出的问题.在我的工作中,我将这组异常类型称为*critical exceptions*,我从[`ErrorHandler.IsCriticalException()`](http://msdn.microsoft.com/en-us/library/microsoft. visualstudio.errorhandler.iscriticalexception.aspx). (2认同)