C# finally Block

In this chapter you will learn:

  1. What is finally Block
  2. How to use finally block in exception handling
  3. Example for finally Block
  4. finally is always executed
  5. Dispose a StreamWriter in 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 {/*from ww w .ja  v  a 2  s.c  o m*/
    // 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  ava  2s  .  c  o 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;/*w w  w  .j ava 2  s  . c om*/
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;/*from  w  w  w . j  a v  a 2s  .c o  m*/
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.

Next chapter...

What you will learn in the next chapter:

  1. What is C# throw statement
  2. Throwing an exception
  3. Example throw statement
  4. Rethrowing an exception
  5. Throw Exception in finally statement
Home »
  C# Tutorial »
    C# Language »
      C# Exception
C# Exception
C# Exception classes
C# try Statements and Exceptions
C# catch Clause
C# finally Block
C# throw statement
C# System Exception