O'Reilly logo

C# 5.0 Unleashed by Bart De Smet

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required