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