O'Reilly logo

C# 2010 All-in-One For Dummies® by Stephen R. Davis, Charles Sphar, Bill Sempf

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Chapter 9. Some Exceptional Exceptions

In This Chapter

  • Handling errors via return codes

  • Using the exception mechanism instead of return codes

  • Plotting your exception-handling strategy

I know it's difficult to accept, but occasionally a method doesn't do what it's supposed to do. Even the ones I write — especially the ones I write — don't always do what they're supposed to. Users are notoriously unreliable as well. No sooner do you ask for an int than a user inputs a double. Sometimes, the method goes merrily along, blissfully ignorant that it is spewing out garbage. However, good programmers write their methods to anticipate problems and report them as they occur.

Note

I'm talking about runtime errors, not compile-time errors, which C# spits out when you try to build your program. Runtime errors occur when the program is running, not at compile time.

The C# exception mechanism is a means for reporting these errors in a way that the calling method can best understand and use to handle the problem. This mechanism has a lot of advantages over the ways that programmers handled errors in the, uh, good old days. Let's revisit yesteryear so that you can see.

This chapter walks you through the fundamentals of exception handling. You have a lot to digest here, so lean back in your old, beat-up recliner.

Using an Exceptional Error-Reporting Mechanism

C# introduces a completely different mechanism for capturing and handling errors: the exception. This mechanism is based on the keywords try, catch, throw ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required