Using a finally block
suggest changeThe 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();
}
}
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents