加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-15 19:57:57 所属栏目:百科 来源:网络整理
导读:连接数据库时是否使用关键字catch或处理C#中的异常?或者我应该在使用中的所有数据库方法中使用try catch块?使用try catch是否会创建不必要的代码? using (var db = new ApplicationContext()){ try { /* Query something */ } catch(Exception e) { logge
连接数据库时是否使用关键字catch或处理C#中的异常?或者我应该在使用中的所有数据库方法中使用try catch块?使用try catch是否会创建不必要的代码?

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

解决方法

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

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

should I use try catch block in all of my database methods inside the 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
}

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读