C# finally Block

Description

A finally block always executes-whether or not an exception is thrown and whether or not the try block runs to completion.

finally blocks are typically used for cleanup code.

Syntax

The general form of a try/catch that includes finally is shown here:


try {//  ww  w.  j  a  v  a  2  s.c om
    // block of code to monitor for errors
}
catch (ExcepType1 exOb) {
    // handler for ExcepType1 
}
catch (ExcepType2 exOb) {
    // handler for ExcepType2 
}
.
.
.
finally {
    // finally code
}

Example

The finally block will be executed whenever execution leaves a try/catch block.


using System; /*from   w  w w. j  av a  2  s  .  co m*/
 
class MainClass { 
  public static void Main() { 
 
    Console.WriteLine("Receiving "); 
    try { 
      int i=1, j=0;
      
      i = i/j; 

    } 
    catch (DivideByZeroException) { 
      Console.WriteLine("Can't divide by Zero!"); 
      return; 
    } 
    catch (IndexOutOfRangeException) { 
      Console.WriteLine("No matching element found."); 
    } 
    finally { 
      Console.WriteLine("Leaving try."); 
    } 
  }   
  
}

The code above generates the following result.

Example 2

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


using System;//from ww  w .j  a  v a2s .  c  o  m
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);
        }
    }
}

The code above generates the following result.

Example 3

Dispose a StreamWriter in finally block


using System;//w w  w .  j  av  a  2s. c om
using System.IO;

public sealed class MainClass
{
    static void Main(){
        StreamWriter sw = new StreamWriter("Output.txt");
        try {
            sw.WriteLine( "This is a test of the emergency dispose mechanism" );
        }
        finally {
            if( sw != null ) {
                ((IDisposable)sw).Dispose();
            }
        }
    }
}

The code above generates the following result.





















Home »
  C# Tutorial »
    C# Language »




C# Hello World
C# Operators
C# Statements
C# Exception