C# Finally Keyword

In C#, the finally block plays a crucial role in managing exceptions. This block is essential for executing clean-up operations that must run regardless of whether an exception is thrown or not. It is particularly handy for tasks like closing files, freeing up database resources, or terminating a database connection. Placed after the try/catch block, the finally block guarantees its code will always be executed, ensuring dependable resource management within the program.

Syntax of Finally keyword:

It has the following syntax.

Example

try

{

    // Statements that can cause errors

}

catch (ExceptionType1 ex)

{

    // Error handling code

}

Finally

{	

// clean up code that always executes

}

In this syntax,

  • Try: The try block holds the code that might throw an exception.
  • Catch: The catch block handles the exception if it occurs.
  • Finally: The finally block executes in every case, whether an exception is raised or not.
  • Simple finally block Example in C#

Let's consider an illustration to demonstrate the finally block within C# exception handling.

Example

Example

using System;

class Tpt

{

    static void Main()

    {	

        try

        {

            Console.WriteLine("Enter any positive number:");

            int x, r;

            x = Convert.ToInt32(Console.ReadLine());

            r = 10 / x; 

            Console.WriteLine("The result is " + r);

        }

        catch (FormatException m)

        {

            Console.WriteLine("Please enter any valid number.");

        }

        catch (DivideByZeroException m)

        {

            Console.WriteLine("Division by zero is not allowed.");

        }

        finally

        {

            Console.WriteLine("Finally block has been executed.");

        }

        Console.WriteLine("The program continues execution after exception handling.");

    }

}

Output:

It has the following output:

Case 1: (Valid Input)

If a positive value is input, the result will be:

Example

Enter any positive number:

5

The result is 2

Finally block has been executed.

The program continues execution after exception handling.

Case 2: (Invalid Input)

If an alphabetical value is provided, the result will be:

Example

Enter any number for your choice:

abc	

Please enter any valid number.

Finally block has been executed.

The program continues execution after exception handling.

Case 3: (Divide by Zero)

If we enter the 0 number, the output would be:

Example

Enter any number for your choice:

0

Division by zero is not allowed.

Finally block has been executed.

The program continues execution after exception handling.

Explanation:

In this instance, we showcase the functionality of the finally block in C# exception handling. Initially, we set up the try block where the user is asked to input a number for a division operation. If the user provides a correct input, the program proceeds and displays the result. In case of invalid inputs like zero or a non-numeric character, an exception is triggered. Nonetheless, the finally block is guaranteed to run regardless of the validity of the user input.

Characteristics of Finally Blocks in C#

Several characteristics of the finally block in C# are as follows:

  • The finally block runs in all cases, no matter whether an exception is thrown or not.
  • A finally block can be utilized without the catch block.
  • It is used for tasks like closing files, releasing the database, or disconnecting from a database.
  • A finally block doesn't allow the conditional statement, including break, continue, or return.
  • Execution of the finally block without a catch block

In C#, the finally block can be employed independently of a catch block, ensuring its execution follows the try block. This functionality proves beneficial when executing cleanup tasks without directly managing exceptions.

C# finally block Example without a catch block:

Let's consider an example where we utilize the finally block in C# without the presence of a catch block.

Example

Example

using System;

class TPT

{

    static void Main()

    {

        try

        {

            Console.WriteLine("Welcome to C# Programmingtech");

            int n1 = 80;

            int res1 = n1 / 2;

            Console.WriteLine($"The division of two numbers is: {res1}");        

}

        finally

        {

            Console.WriteLine("Finally block has been executed successfully.");

        }

        Console.WriteLine("The program continues after the try finally.");

    }

}

Output:

Output

Welcome to C# Programmingtech

The division of two numbers is: 40

Finally block has been executed successfully.

The program continues after the try finally.

Explanation:

In this instance, we demonstrate the utilization of finally blocks in the absence of a catch block. Within the try block, a message is printed, and a division operation is carried out. Subsequently, the finally block is triggered automatically, displaying the confirmation message.

Execution of the finally block with an exception

In C# development, when an exception occurs within the try block, the finally block will still be executed. This guarantees that essential tasks such as resource release or clean-up operations are consistently carried out.

C# Example using a finally block with exceptions

Let's consider an example to demonstrate the finally block in C# when handling exceptions.

Example

Example

using System;

class C# Tutorial

{

    static void Main()

    {	

        try

        {

            int n = 1000;

            int x = n / 0; 

            Console.WriteLine("The division  of two numbers is " + x);

        }

        catch ( DivideByZeroException m )

        {

            Console.WriteLine("Error: " + m.Message );

        }

        finally

        {

            Console.WriteLine("Finally block executed.");

        }

    }

}

Output:

Output

Error: Attempted to divide by zero.

Finally block executed.

Explanation:

In this instance, we attempt to perform a division operation by dividing 10 by 0 within a try block. Since dividing by zero is not allowed, it triggers a runtime error. Subsequently, the program proceeds to the catch block where it identifies the error and presents the corresponding error message. Following the execution of the catch block, the finally block is executed.

C# Example using a finally block for resource clean-up

Let's consider an example to demonstrate the finally block for resource cleanup.

Example

Example

using System;

using System.IO;

class Program

{

    static void Main()

    {

        StreamReader r = null;

        try

        {

            r = new StreamReader("test.txt");

            string content = r.ReadToEnd();

            Console.WriteLine(content);

        }

        catch (FileNotFoundException m)

        {

            Console.WriteLine("File not found: " + m.Message);

        }

        finally

        {

            if (r != null)

            {

                r.Close();   // Clean up resource

                Console.WriteLine("File stream closed successfully.");

            }

        }

    }

}

Output:

Output

File not found: Could not find file "/home/compiler/ test.txt "

Explanation:

In this instance, the code tries to open or read a specific file. If the file cannot be located, the catch block manages the FileNotFoundException and presents an error message. Finally, the code inside the finally block is executed. This block verifies whether the r object is not null and proceeds to close it in order to free up system resources.

Important Points in the finally block in C#

Several important points of the finally block in C# are as follows:

  • In C#, multiple finally blocks in the same block of the program are not allowed.
  • It is an optional block.
  • A single try block contains multiple catch blocks, but only one finally block is permitted.
  • Conclusion

In summary, the C# finally block plays a crucial role in managing exceptions by addressing runtime errors and preserving the regular program flow. This block stands out as a fundamental aspect of exception handling, guaranteeing the execution of clean-up code regardless of any exceptions. Its significance lies in tasks such as closing files, releasing database connections, or disconnecting from a database.

C# finally Block FAQs

1) What is a finally block in C#?

In C#, the finally clause plays a crucial role in exception handling. It guarantees the execution of clean-up operations regardless of whether an exception is thrown or not. This is particularly beneficial for activities such as closing files, freeing up database resources, or terminating a database connection. The finally block is positioned at the conclusion, following the try and catch blocks.

Is it mandatory to include a finally block while managing an exception?

No, the eventually block is a discretionary section in exception handling. It proves beneficial for actions such as finalizing files, freeing up the database, or severing connections from a database.

3) When does the finally block execute?

The finally block is executed in all scenarios. It is always executed regardless of whether exceptions are thrown. The finally block is executed after the try and catch blocks finish their execution.

Yes, in C#, a finally block can exist without a catch block.

Yes, the finally block can be employed independently of a catch block.

Example

try	

{

    Console.WriteLine(" Try block. ");

}

finally

{

    Console.WriteLine("Finally block executed.");

}

When exceptions arise within the finally block, they are managed in a similar manner to how they are handled in other parts of the code.

If an error arises within the finally block, it will override any exception that is triggered in the try or catch block.

Input Required

This code uses input(). Please provide values below: