The finally Clause

Another aspect to exception handling is found in the finally clause that can be associated with a try statement. To illustrate its purpose, let’s rewrite our PrintFile method using some more low-level primitives from the System.IO namespace:

static void PrintFile(string path){    FileStream fs = File.OpenRead(path);    StreamReader sr = new StreamReader(fs);    string line;    while ((line = sr.ReadLine()) != null)    {        Console.WriteLine(line);    }}

This code has severe flaws in it. Even if we succeed in opening the file on the first line, we never close the FileStream object, which causes leakage. Wait a minute, didn’t the CLR have a garbage collector to take care of this? True, but as you will see, the garbage collector ...

Get C# 4.0 Unleashed now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.