在 C# 数据库相关 类 中使用和尝试捕获?

Using and try catch in C# database related classes?

连接到数据库时,在 C# 中使用关键字捕获或处理异常吗?或者我应该在使用中的所有数据库方法中使用 try catch 块吗?使用 try catch 会产生不必要的代码吗?

using (var db = new ApplicationContext())
{        
    try {
       /* Query something */
    } catch(Exception e) {
       logger.Debug(e);
    }
}  

using 块不会为您 "handle" 例外,它只确保 Dispose() 方法在 IDisposable 对象上被调用(在这种情况下,您的db 实例),即使发生异常。所以是的,您需要在需要的地方添加 try-catch 个块。

也就是说,一般来说,您只想捕获可以实际对它们做一些有意义的事情的异常。如果您只需要记录异常,请考虑在调用堆栈中较高的单个位置进行异常处理,这样您就不必在代码中到处乱扔 try-catch 块。

您可以阅读 using Statement here 了解它的实际作用,以及它是如何翻译的。

编辑:

如果出于某种原因,您选择将 try-catch 块保留在原处,至少,请确保重新抛出异常而不是吞下它,这就像扫除下面的烂摊子地毯并假装一切都很好。另外,确保在不丢失宝贵的堆栈跟踪的情况下重新抛出它。像这样:

using (var db = new ApplicationContext())
{        
    try {
       /* Query something */
    } catch(Exception e) {
       logger.Debug(e);
       throw; // rethrows the exception without losing the stack trace.
    }
}

编辑 2:Eric Lippert 关于 exception handling.

的非常好的博客条目

using 关键字用于块完成后,using 参数内的对象(在本例中为上下文)被正确处理,所以是的,您仍然需要使用 try-catch 关键字处理异常。

您的 using 将由 C# 编译器转换为底层代码,由 8.13 The using statement:

{
    var db = new ApplicationContext();
     try
     {
       try {
          /* Query something */
       } catch(Exception e) {
          logger.Debug(e);
       }
     }
     finally
     {
       // Check for a null resource.
       if (db!= null)
        // Call the object's Dispose method.
           ((IDisposable)myRes).Dispose();
     }
}

所以,我的意见,对于你的情况,我认为没有 using 声明更好,它会更清晰一些,步骤也会更少:

 var db = new ApplicationContext();
 try
 {
    /* Query something */                  
 }
 catch(Exception e)
 {
    logger.Debug(e);
 }
 finally
 {
    if (db!= null)
    {
      ((IDisposable)myRes).Dispose();
    }
 }

因为using它只是一个语法糖

P.S: try 语句的性能开销很小,你可以保留你的代码。

由于using不处理任何异常,您可能需要交换。

usingtry-finally 的语法糖,所以你知道,即使构造函数没有处理异常,连接也将关闭或根本不建立。

try {
    using (var db = new ApplicationContext())
    {        

       /* Query something */

    }  
} catch(Exception e) {
   logger.Debug(e);
}

Does using keyword catch or handle exceptions in C# when connecting to a database?

A using 在逻辑上等同于 try-finally,所以是的,它处理异常,但它不会 停止 异常。 finally 传播异常。

should I use try catch block in all of my database methods inside the using?

。 try-catch 应该 之外 using。这样它将保护资源创建。

Does using try catch create unnecessary code?

我不知道这个问题是什么意思。

有些问题你没有问:

Should I catch all exceptions for logging and then fail to re-throw them?

。仅捕获并吃掉您知道如何处理的异常。如果您想记录异常,那么在完成记录后 重新抛出 它们;其他代码可能想要处理它们。

What is the correct way to write this code?

分离您的顾虑。您有三个顾虑:

  • 释放资源
  • 记录所有异常
  • 处理预期的外生异常

其中每一个都应由单独的语句处理:

try // handle exogenous exceptions
{  
   try // log all exceptions
   {
       using(var foo = new Foo()) // dispose the resource
       {
           foo.Bar();
       }
   }
   catch(Exception x)
   {
       // All exceptions are logged and re-thrown.
       Log(x);
       throw;
   }
}
catch(FooException x) 
{
    // FooException is caught and handled
}

如果您的目标是仅记录 未处理的 异常,则反转两个处理程序的嵌套,或使用其他机制,例如应用程序域的未处理异常事件处理程序。