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 ...

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

O’Reilly members experience live online training, plus books, videos, and digital content from nearly 200 publishers.