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