Introducing Exceptions

With exceptions entering the picture, you can separate error handling from the regular flow of an application in a block-structured manner. For example, the following example illustrates the use of the System.IO .NET Framework APIs to read a file from disk:

IEnumerable<Customer> ReadCustomersFrom(string file) {    try {        using (FileStream fs = File.OpenRead(file)) {            using (StreamReader sr = new StreamReader(fs)) {                // Read from the file, creating Customer instances to return...            }        }    }    catch (IOException ex) {        // If we can handle this exception somehow, we can do it here.    }}

Various methods used in the preceding code can throw ...

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

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