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. For instance, consider the System.IO.File.OpenRead API, where the following exceptions are documented:

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

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.