C# try catch finally

Summary: in this tutorial, you’ll learn how to use the C# try...catch...finally statement to handle exceptions and clean up resources.

Introduction to the C# try…catch…finally statement

The try...catch statement has an optional finally clause as follows:

try
{
    // execute statement
}
catch (Exception e)
{
    // handle execeptions
}
finally
{
    // always execute
}Code language: PHP (php)

When a try...catch statement contains a finally, it always executes the finally block whether an exception occurs inside the try block or not:

  • If no exception occurs inside the try block, the control skips over any catch block and goes to the finally block.
  • If an exception occurs inside the try block, the appropriate catch clauses are executed followed by the execution of the finally block.

It’s important to note that even if the try clause has a return statement, the finally block will always execute.

Also, the finally block cannot contain a return statement. Otherwise, the program will fail to compile.

In practice, you often use the finally block to clean up the resources such as closing a stream or a database connection.

C# try…catch…finally statement example

Let’s take some examples of using the try...catch..finally statment.

1) Using the C# try…catch…finally statement example

The following program reads a text file line by line and displays the file contents to the console. It uses the try...catch...finally statement to handle exceptions:

StreamReader? reader = null;
try
{
    reader = new StreamReader(@"C:\csharptutorial\test.txt");
    string? line = reader.ReadLine();
    while (line != null)
    {
        Console.WriteLine(line);
        line = reader.ReadLine();
    }
}
catch (Exception e)
{
    Console.WriteLine($"Error: {e.Message}");
}
finally
{
    //close the file
    if (reader != null) reader.Close();
}Code language: PHP (php)

In this example, the finally block closes the stream reader whether an exception occurs inside the try block or not.

2) Using the C# try…catch…finally statement with the return statement

The following illustrates the control flow of the program when using a return statement inside the try block:



int Test()
{
    int result = 100;
    try
    {
        return result;
    }
    catch (Exception e) 
    {
        Console.WriteLine(e.Message);
    } 
    finally
    {
        result = 200;
        Console.WriteLine("Execute the finally block...");
    }

    // these statement won't execute
    Console.WriteLine("Bye!");
    return result;
}

Console.WriteLine(Test());Code language: PHP (php)

Output:

Execute the finally block...
100Code language: JavaScript (javascript)

In this example, the program returns the result variable in the try block. The program also executes the finally block. However, it ends immediately as long as it reaches the end of the finally block.

Summary

  • Use the C# try...catch...finally block to handle exceptions and clean up the resources.
  • The finally block always executes whether an exception occurs in the try block or not.
Was this tutorial helpful ?