Open In App

C# finally Keyword

Last Updated : 31 Jan, 2025
Summarize
Comments
Improve
Suggest changes
Share
Like Article
Like
Report

finally keyword in C# is an important component of exception handling. It makes sure that specific cleanup code is always executed, whether an exception is thrown or not. This makes it ideal for releasing resources such as file handles, database connections, or network streams. The finally block is used in conjunction with try and catch blocks.

  • The finally block always executes, even if an exception occurs or a return statement is used in the try or catch blocks.
  • A finally block can be used without a catch block, making it versatile for scenarios where exceptions are not explicitly handled.
  • It is primarily used to release or clean up resources like file streams or database connections.
  • The finally block does not allow control transfer statements such as return, break, or continue.

Example 1: Basic Usage of finally

C#
// C# Program to demonstrate 
// the use of finally block
using System;

class Geeks
{
    static void Main()
    {
        try
        {
            // Simulating an exception
            Console.WriteLine("Inside try block");
            throw new Exception("An error occurred!");
        }
        catch (Exception ex)
        {
            // Handling the exception
            Console.WriteLine($"Caught exception: {ex.Message}");
        }
        finally
        {
            // Cleanup code
            Console.WriteLine("Finally block executed");
        }
    }
}

Output
Inside try block
Caught exception: An error occurred!
Finally block executed

Explanation: In the above example, the try block throws an exception. The catch block handles the exception. The finally block executes cleanup code and makes sure it runs regardless of exceptions.

Syntax of finally

try

{ // Code that may throw an exception }

catch (ExceptionType e)

{ // Code to handle the exception }

finally

{ // Cleanup code that always executes }

Important Points:

  • In C#, multiple finally blocks in the same program are not allowed.
  • The finally block does not contain any return, continue, break statements because it does not allow controls to leave the finally block.
  • You can also use finally block only with a try block means without a catch block but in this situation, no exceptions are handled.
  • The finally block will be executed after the try and catch blocks, but before control transfers back to its origin.

Example 2: Using finally Without a catch Block

C#
// C# Program of finally without catch block
using System;

class Geeks
{
    static void Main()
    {
        try
        {
            // Code that may cause an exception
            Console.WriteLine("Opening a file..");
        }
        finally
        {
            // Always executed, even without a catch block
            Console.WriteLine("File closed successfully.");
        }
    }
}

Output
Opening a file..
File closed successfully.

Explanation: In this example, the finally block ensures the file is closed even though no exception handling (catch) is implemented.

Example 3: Using finally With Handled Exceptions

C#
// C# Program with finally block 
// handling handled exception
using System;

class Geeks
{
    static void Main()
    {
        try
        {
            // Trying to divide by zero at runtime
            Console.WriteLine("Inside try block");
            int numerator = 10;
            int denominator = 0; 


            int res = numerator / denominator;

            Console.WriteLine("Result of division: " + res);
        }
        catch (DivideByZeroException)
        {
            // Handling the exception
            Console.WriteLine("Caught: Cannot divide by zero");
        }
        finally
        {
            Console.WriteLine("Finally block executed.");
        }
    }
}

Output
Inside try block
Caught: Cannot divide by zero
Finally block executed.

Explanation: In the above example the try block raises a DivideByZeroException. The catch block handles it, and the finally block ensures cleanup.

Example 4: Using finally With Unhandled Exceptions

C#
// C# Program with finally block handling 
// runtime division by zero exception
using System;

class Geeks
{
    static void Main()
    {
        try
        {
            // Trying to divide by zero at runtime
            Console.WriteLine("Attempting division...");
            int numerator = 10;
            int denominator = 0; 

            // Simulating runtime division by zero
            int res = numerator / denominator; 

            Console.WriteLine("Result of division: " + res);
        }
        catch (DivideByZeroException ex)
        {
            // Handling the divide by zero exception
            Console.WriteLine("Caught exception: " + ex.Message);
        }
        finally
        {
            // Executes even though the exception is handled
            Console.WriteLine("Finally block executed");
        }
    }
}

Output
Attempting division...
Caught exception: Attempted to divide by zero.
Finally block executed

Explanation: In the above example, the try block raises an exception DivideByZeroException, that is not handled, but the finally block still executes, ensuring cleanup is performed.


Next Article
Article Tags :

Similar Reads