如果在使用语句中发生异常,对象是否仍然处理? [英] If an Exception happens within a using statement does the object still get disposed?

查看:147
本文介绍了如果在使用语句中发生异常,对象是否仍然处理?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果使用声明中发生异常,对象是否仍然处理?

If an Exception happens within a using statement does the object still get disposed?

我问的原因是因为我正在决定是否在整个代码块或内部使用语句中放置一个尝试。记住某些例外是在catch块内被设计重新抛出的。

The reason why I'm asking is because I'm trying to decide on whether to put a try caught around the whole code block or within the inner using statement. Bearing in mind certain exceptions are being re-thrown by design within the catch block.

using (SPSite spSite = new SPSite(url))
{
       //Get the Web
       using (SPWeb spWeb = spSite.OpenWeb())
       {

           // Exception occurs here

       }
}


推荐答案

p>是的,他们会。

using(SPWeb spWeb = spSite.OpenWeb())
{
  // Some Code
}

相当于

{
  SPWeb spWeb = spSite.OpenWeb();
  try
  {

    // Some Code
  }
  finally
  {
    if (spWeb != null)
    {
       spWeb.Dispose();
    }
  }
}



编辑



在回答这个问题后,我写了一篇关于 IDisposable and Using 在我的博客中。

这篇关于如果在使用语句中发生异常,对象是否仍然处理?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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