Light Mode Image

C# Finally Block

The finally block is used in conjunction with a try block to define a section of code that will be executed regardless of whether an exception is thrown or not. The finally block is optional and follows the try block.

 

Here's the basic structure,

try
{
    // Code that might throw an exception
}
catch (Exception ex)
{
    // Code to handle the exception
}
finally
{
    // Code that will always be executed, whether an exception is thrown or not
}

 

The try block contains the code that might throw an exception.

 

If an exception occurs, the control is transferred to the catch block where you can handle the exception.

 

The finally block contains code that will always be executed, regardless of whether an exception is thrown or caught.

 

The primary use of the finally block is to ensure that certain cleanup or resource release operations are performed, regardless of whether an exception occurs. For example, closing a file, releasing database connections, or cleaning up other resources.

 

Here's an example:

FileStream file = null;
try
{
    file = new FileStream("example.txt", FileMode.Open);
    // Code that might throw an exception
}
catch (IOException ex)
{
    // Code to handle the IOException
}
finally
{
    // Code that will always be executed, whether an exception is thrown or not
    file?.Close(); // Close the file even if an exception occurred
}

 

In this example, the FileStream is created within the try block, and the finally block ensures that the file is closed, even if an exception occurs.

 

The ?. operator is used to check if the file object is not null before calling the Close method.