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
我想知道哪些其他例外不适合捕获,或者与不良做法有关.
以下是您不应该捕获的所有异常的列表:
这是异常处理的最佳实践:
如果您不知道如何处理异常,请不要抓住它.
这可能听起来很讽刺,但它们都是正确的,而这就是你需要知道的.
| 归档时间: |
|
| 查看次数: |
1525 次 |
| 最近记录: |