Executing a Statement Finally

Executing a Statement Finally

In addition to the try and catch blocks, finally blocks can be used to ensure that certain code is executed, regardless of whether an exception was thrown or not.

Here’s an example of how to use a try-catch-finally block in ASP.NET:

SqlConnection connection = null;

try

{

    // Open database connection

    connection = new SqlConnection(connectionString);

    connection.Open();

    // Execute database query

    SqlCommand command = new SqlCommand(query, connection);

    SqlDataReader reader = command.ExecuteReader();

    // Process query results

    while (reader.Read())

    {

        // …

    }

    // Close reader

    reader.Close();

}

catch (Exception ex)

{

    // Handle the exception

    // Log the exception

    // Display a user-friendly error message

}

finally

{

    // Close database connection

    if (connection != null)

    {

        connection.Close();

    }

}

In this example, the finally block is used to close the database connection, regardless of whether an exception was thrown or not. This is important because leaving database connections open can cause performance problems and resource leaks.

The finally block will always be executed, regardless of whether an exception was thrown or not. This ensures that any cleanup code that needs to be executed, such as closing files or releasing resources, is always executed.

Note that the finally block should only contain code that needs to be executed regardless of whether an exception was thrown or not. It should not contain code that can throw exceptions itself, as this can cause unexpected behavior.

Apply for ASP.NET Certification Now!!

https://www.vskills.in/certification/certified-aspnet-programmer

Back to Tutorial

Share this post
[social_warfare]
Using Try Catch in Risky Situations
Derivatives

Get industry recognized certification – Contact us

keyboard_arrow_up