Monday, October 16, 2017

finally block and using statement in C#

In addition to try and catch C# got so-called finally block whose purpose is to free resources allocated within try block.

using System.IO;

namespace ConsoleApp
{
    class Program
    {
        static void Main(string[] args)
        {
            StreamWriter sw = null;

            try
           {
                sw = new StreamWriter("myFile.txt");
                sw.WriteLine("Hello");
            }
            finally
            {
                if (sw != null)
                {
                    sw.Dispose();
                }
            }
        }
    }
}

finally block will get executed even if something in your try block throws an exception. There is much more convenient way to create try-finally block around your code though, its called using statement:

using System.IO;

namespace ConsoleApp
{
    class Program
    {
        static void Main(string[] args)
        {
            using(StreamWriter sw = new StreamWriter("myFile.txt"))
           {
                sw.WriteLine("Hello");
            }
        }
    }
}

If you need to be able to handle exception you're gonna have to use the previous syntax plus catch block as using statement can't help you with that:

using System.IO;

namespace ConsoleApp
{
    class Program
    {
        static void Main(string[] args)
        {
            StreamWriter sw = null;

            try
           {
                sw = new StreamWriter("myFile.txt");
                sw.WriteLine("Hello");
            }
            catch(IOException e)
            {
             // Handle exception before resource gets freed in finally block.
            }
            finally
            {
                if (sw != null)
                {
                    sw.Dispose();
                }
            }
        }
    }
}

No comments:

Post a Comment