C#:“using”指令和try / catch块 [英] C#: "using" directive and try/catch block

查看:309
本文介绍了C#:“using”指令和try / catch块的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道如何使用try / catch块来处理数据库调用,并且知道如何在使用try / finally结构的情况下使用using指令。



<但是,我可以混合他们吗?我的意思是当我使用使用指令,我可以使用try / catch结构,因为我仍然需要处理可能的错误?

解决方案

p>当然你可以这样做:

  using(var con = new SomeConnection()){
try {
//做一些东西
}
catch(SomeException ex){
//错误处理
}
}

使用由编译器翻译为,所以它与嵌套 try..catch 里面 try..finally


I know how to use try/catch block in case of database calls and know how to use "using" directive in context of using try/finally construction as well.

But, can I mix them? I mean when I use "using" directive can I use try/catch construction as well because I still need to handle possible errors?

解决方案

Of course you can do it:

using (var con = new SomeConnection()) {
    try {
        // do some stuff
    }
    catch (SomeException ex) {
        // error handling
    }
}

using is translated by the compiler into a try..finally, so it's not very different from nesting a try..catch inside a try..finally.

这篇关于C#:“using”指令和try / catch块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆