0
0
C Sharp (C#)programming~5 mins

Finally block behavior in C Sharp (C#)

Choose your learning style9 modes available
Introduction

The finally block lets you run code that must happen no matter what, like cleaning up or closing files.

You open a file and want to make sure it closes even if an error happens.
You start a network connection and need to close it whether the work succeeds or fails.
You allocate resources like memory or database connections and want to release them safely.
You want to show a message or log something after trying some code, regardless of errors.
Syntax
C Sharp (C#)
try
{
    // code that might cause an error
}
catch (Exception e)
{
    // code to handle the error
}
finally
{
    // code that always runs
}

The finally block runs after try and catch, no matter what.

You can use finally with or without a catch block.

Examples
This example shows a finally block without a catch. The message in finally always prints.
C Sharp (C#)
try
{
    Console.WriteLine("Trying something...");
}
finally
{
    Console.WriteLine("Always runs.");
}
This example catches an error and still runs the finally block.
C Sharp (C#)
try
{
    int x = 5 / 0;
}
catch (DivideByZeroException e)
{
    Console.WriteLine("Caught division by zero.");
}
finally
{
    Console.WriteLine("Cleanup code runs.");
}
Sample Program

This program tries to divide by zero, catches the error, and then runs the finally block. The program then continues normally.

C Sharp (C#)
using System;

class Program
{
    static void Main()
    {
        try
        {
            Console.WriteLine("Start try block.");
            int result = 10 / 0; // This causes an error
            Console.WriteLine("This line will not run.");
        }
        catch (DivideByZeroException)
        {
            Console.WriteLine("Caught division by zero error.");
        }
        finally
        {
            Console.WriteLine("Finally block always runs.");
        }
        Console.WriteLine("Program continues.");
    }
}
OutputSuccess
Important Notes

If there is a return inside try or catch, the finally block still runs before returning.

Use finally to release resources like files or connections safely.

Summary

The finally block runs no matter what happens in try or catch.

It is useful for cleanup tasks that must always happen.

You can use finally with or without catch.