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


C# Examples » Language Basics » Finally »

 

finally block is always executed even if an exception was thrown in the try









    
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);
                }
        }
}
    
   
  
   



Output

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()


HTML code for linking to this page:

Follow Navioo On Twitter

C# Examples

 Navioo Language Basics
» Finally