About This eBook by Bart De Smet

Safari, the world’s most comprehensive technology and business learning platform.

Find the exact information you need to solve a problem on the fly, or go deeper to master the technologies and skills you need to succeed

Start Free Trial

No credit card required

O'Reilly logo

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

Find the exact information you need to solve a problem on the fly, or go deeper to master the technologies and skills you need to succeed

Start Free Trial

No credit card required