When and What to Catch

Handling exceptions correctly is a huge responsibility for framework and application developers. For that reason alone, it’s important to give some guidelines on when and what to catch.

Let’s start with the latter question: what exceptions to catch. You first want to know which exceptions can be thrown by the APIs being used; for this information, documentation proves invaluable. As an example, consider the System.IO.File.OpenRead API, where the following exceptions are documented:

ArgumentException—The path is a zero-length string, contains only whitespace or contains one or more invalid characters as defined by InvalidPathChars.

ArgumentNullException—The path is null.

PathTooLongException—The specified path, filename, ...

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

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