C# Keywords Tutorial Part 32: finally

C# Keywords Tutorial Part 32: finally

In C#, the “finally” keyword is used in a try-catch-finally block to specify a block of code that will be executed regardless of whether an exception is thrown or not. The finally block is often used to perform cleanup tasks, such as closing files or releasing resources, that must be done regardless of whether an exception is thrown or not. In this blog post, we will explore the usage of the “finally” keyword in C# with code examples.

Consider the following code snippet:

StreamReader reader = null;
try
{
    reader = new StreamReader("file.txt");
    string line = reader.ReadLine();
    Console.WriteLine(line);
}
catch (IOException ex)
{
    Console.WriteLine("An error occurred while reading the file: " + ex.Message);
}
finally
{
    if (reader != null)
    {
        reader.Close();
    }
}

The code snippet above creates a StreamReader instance to extract the contents of a file named “file.txt”. The first line of the file is then read and displayed on the console. Any exceptions that arise during the file read operation are caught and an error message is printed to the console. The code concludes by verifying if the reader object is null and, if not, closing the file through the Close() method.

By implementing the finally block in this example, the file is always closed regardless of any exceptions that might be thrown. This is crucial as keeping files open could cause issues such as hindering other processes from accessing the file or corrupting data.

Here’s another illustration of how the finally block can be utilized to free up resources:

MyResource resource = null;
try
{
    resource = new MyResource();
    resource.DoWork();
}
finally
{
    if (resource != null)
    {
        resource.Dispose();
    }
}

In the above code, we are creating a custom resource object called “MyResource” and calling the “DoWork” method on it. Finally, we are checking if the resource object is null and, if not, we are calling the Dispose() method on it. The Dispose() method releases any resources that the object is holding onto, such as file handles or network connections.

Share this post

Leave a Reply

Your email address will not be published. Required fields are marked *