finally block is always executed even if an exception was thrown in the try : Finally « Language Basics « C# / CSharp Tutorial






using System;
using System.IO;

class Processor
{
    public void ProcessFile()
    {
        FileStream f = new FileStream("wrongNameFile.txt", FileMode.Open);
        try
        {
            StreamReader t = new StreamReader(f);
            string    line;
            while ((line = t.ReadLine()) != null)
            {
                Console.WriteLine(line);
            }
        }
        finally
        {
            f.Close();
        }
    }
}
class Test
{
    public static void Main()
    {
        Processor processor = new Processor();
        try
        {
            processor.ProcessFile();
        }
        catch (Exception e)
        {
            Console.WriteLine("Exception: {0}", e);
        }
    }
}
Exception: System.IO.FileNotFoundException: Could not find file 'C:\Java_Dev\WEB\dev\CSharp\wrongNam
eFile.txt'.
File name: 'C:\Java_Dev\WEB\dev\CSharp\wrongNameFile.txt'
   at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
   at System.IO.FileStream.Init(String path, FileMode mode, FileAccess access, Int32 rights, Boolean
 useRights, FileShare share, Int32 bufferSize, FileOptions options, SECURITY_ATTRIBUTES secAttrs, St
ring msgPath, Boolean bFromProxy)
   at System.IO.FileStream..ctor(String path, FileMode mode)
   at Processor.ProcessFile()
   at Test.Main()








1.19.Finally
1.19.1.Using finally
1.19.2.finally block is always executed even if an exception was thrown in the try
1.19.3.Dispose a StreamWriter in finally block