Using a finally block

suggest change

The finally block of a try-finally or try-catch-finally runs whether or not an exception was thrown. It does not run if a StackOverflowException brings the process down, or if Environment.FailFast is called.

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, FileMode.Open);
}
catch (FileNotFoundException)
{
    Console.WriteLine("File '{0}' could not be found.", filename);
}
finally
{
    if (fileStream != null)
    {
        fileStream.Dispose();
    }
}

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents