Disposables, Using & Try/Catch Blocks

后端 未结 6 1402
一向
一向 2020-12-19 05:56

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

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

FileStream fs = null         


        
6条回答
  •  青春惊慌失措
    2020-12-19 06:16

    Don't worry, it will clean up as expected and is cleaner than your original.

    In fact it's much more common to have a try/finally aka using statement in your business logic, and a try/catch in a top-level handler in the UI tier or at a physical tier boundary. Something like:

    try
    {
        DoStuffWithFile("foo.txt");
    }
    catch(Exception ex)
    {
       ...
    }
    

    and

    public void DoStuffWithFile(string fileName)
    {
        using(FileStream fs = File.Open(fileName,...))
        {
            // Do Stuff
        }
    }
    

提交回复
热议问题