你能抓住 using 块吗?
可以在 using 块内捕获异常吗?如果可以,语法是什么?
那么,类似于以下内容:
using (var creatingThing = new MyCreatingThing())
{
creatingThing.CreateSomething();
catch()
{
creatingThing.Rollback();
}
}
这可以做到吗?或者我需要手动编写此代码(即不使用)?
Can exceptions be caught inside a using block, and if so what is the syntax?
So, something like the following:
using (var creatingThing = new MyCreatingThing())
{
creatingThing.CreateSomething();
catch()
{
creatingThing.Rollback();
}
}
Can this be done? Or do I need to write this code manually (ie without a using)?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您可以将 try/catch 放在
using
语句内部,或外部:或者...
但是,您不能只放置一个 catch 块而不放置 try 块。
根据是否需要捕获资源获取表达式引发的异常、是否希望在执行 catch 块之前释放资源以及是否需要访问 catch 块内的资源变量来选择正确的方法。
You can put a try/catch inside the
using
statement, or outside:Or...
However, you can't just put a catch block without a try block.
Choose the right one based on what whether you need to catch exceptions which are thrown by the resource acquisition expression, whether you want the resource to be disposed before your catch block is executed, and whether you need access to the resource variable within the catch block.
您不能隐式加入编译器生成的
try...finally
块(对于using
语句)。您必须添加另一个try
语句,该语句将嵌套在生成的块中:You cannot implicitly enlist in the
try...finally
block that the compiler generates (for theusing
statement). You have to add anothertry
statement, which will be nested within the generated block:请注意, a 使用实际上是幕后的 try/finally,因此这样编写代码可能会更容易:
Note, the a using is really a try/finally under the covers, so it may be easier the code it that way:
当然,只需在 using 中添加 try 即可:
Sure, just add the try inside the using: