Using a finally block

Download .net eBook

Example

The finally { ... } block of a try-finally or try-catch-finally will always execute, regardless of whether an exception occurred or not (except when a StackOverflowException has been thrown or call has been made to Environment.FailFast()).

It can be utilized to free or clean up resources acquired in the try { ... } block safely.

Console.Write("Please enter a filename: ");
string filename = Console.ReadLine();

Stream fileStream = null;

try
{
    fileStream = File.Open(filename);
}
catch (FileNotFoundException)
{
    Console.WriteLine("File '{0}' could not be found.", filename);
}
finally
{
    if (fileStream != null)
    {
        fileStream.Dispose();
    }
}

Stats

Contributors: 4
2016-07-28
Licensed under: CC-BY-SA

Not affiliated with Stack Overflow
Rip Tutorial: info@zzzprojects.com

Download eBook