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