耗材,使用和放大器; try / catch块 [英] Disposables, Using & Try/Catch Blocks

查看:125
本文介绍了耗材,使用和放大器; try / catch块的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

今天有一个心理障碍,需要帮忙验证我的逻辑是不fubar'ed。

Having a mental block today, need a hand verifying my logic isn't fubar'ed.

传统上我会做的文件I / O与此类似:

Traditionally I would do file i/o similar to this:

FileStream fs = null; // So it's visible in the finally block
try
{
   fs = File.Open("Foo.txt", FileMode.Open);

   /// Do Stuff
}
catch(IOException)
{
   /// Handle Stuff
}
finally
{
   if (fs != null)
      fs.Close();
}

不过,这是不是很优雅。

However, this isn't very elegant.

在理想情况下,我想使用使用块处分时,我做的文件流的,但是我不能确定如何使用和try / catch之间的协同作用

Ideally I'd like to use the using block to dispose of the filestream when I'm done, however I am unsure about the synergy between using and try/catch.

这是我想如何实现上述:

This is how i'd like to implement the above:

try
{
   using(FileStream fs = File.Open("Foo.txt", FileMode.Open))
   {
      /// Do Stuff
   }
}
catch(Exception)
{
   /// Handle Stuff
}

不过,我担心使用块中的premature出口(通过抛出异常)可能不允许使用块来完成执行和清理它的对象。我只是偏执,或将在实际工作我想让它的方式吗?

However, I'm worried that a premature exit (via thrown exception) from within the using block may not allow the using block to complete execution and clean up it's object. Am I just paranoid, or will this actually work the way I intend it to?

推荐答案

你只是被偏执的的它会工作的方式,你想让它:)

You're just being paranoid and it will work the way you intend it to :)

using语句相当于一个try / finally块,无论是在try / catch里面还是不行。

A using statement is equivalent to a try/finally block, whether it's inside a try/catch or not.

所以,你的code是类似于:

So your code is similar to:

try
{
   FileStream fs = null;
   try
   {
       fs = File.Open("Foo.txt", FileMode.Open);
       // Do stuff
   }
   finally
   {
       if (fs != null)
       {
           fs.Dispose();
       }
   }
}
catch(Exception)
{
   /// Handle Stuff
}

这篇关于耗材,使用和放大器; try / catch块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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