Chapter 9 Error Handling

What’s in This Chapter

  • Understanding bugs and unexpected conditions
  • Using assertions and code contracts to detect bugs
  • Handling exceptions with try-catch-finally
  • Creating custom exception classes

Wrox.com Downloads for This Chapter

Please note that all the code examples for this chapter are available as a part of this chapter’s code download on the book’s website at www.wrox.com/go/csharp5programmersref on the Download Code tab.

Although it is theoretically possible to write a program that perfectly predicts every conceivable situation that it might encounter, in practice that’s difficult for nontrivial programs. For large applications, it’s practically impossible to plan for every eventuality. Errors in the program’s design and implementation can introduce bugs that give unexpected results. Even if you correctly anticipate every normal condition, users, corrupted databases, and unreliable network communications may give the application values that it doesn’t expect.

Similarly, changing requirements over time may introduce data that the application was never intended to handle. The Y2K bug is a good example. When engineers wrote accounting, auto registration, financial, inventory, and other systems in the 1960s and 1970s, they never dreamed their programs would still be running in the year 2000. At the time, disk storage and memory were relatively expensive, so they stored years as 2-byte values (for example, 89 meant 1989). When the year 2000 rolled ...

Get C# 5.0 Programmer's Reference 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.