Monday, 20 August 2018

C#: finally block

The finally block always executes when the try block exits. This ensures that the finally block is executed even if an unexpected exception occurs. Finally block mainly used to perform cleanup operation like closing file streams, flushing the data etc.,

A try block must associate with at least one catch or finally block.

Program.cs
using System;

class Program
{
   
    static void Main(string[] args)
    {
        try
        {
            int a = 10;
            int b = 0;
            int c = a / b;
        }
        finally
        {
            Console.WriteLine("I am in finally block");
        }

        Console.WriteLine("I am not going to execute");
       
    }
}


Output

Unhandled Exception: System.DivideByZeroException: Attempted to divide by zero.
   at Program.Main(String[] args) in C:\Users\krishna\Documents\Visual Studio 2015\Projects\HelloWorld\HelloWorld\Program.cs:line 12
I am in finally block




Previous                                                 Next                                                 Home

No comments:

Post a Comment