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