Chapter 32

I Take Exception!

In This Chapter

arrow Introducing the exception mechanism for handling program errors

arrow Examining the mechanism in detail

arrow Creating your own custom exception class

I know it’s hard to accept, but occasionally programs don’t work properly — not even mine. The traditional means of reporting a failure within a function is to return some indication to the caller, usually as a return value. Historically, C and C++ programmers have used 0 as the “all clear” indicator — and anything else as meaning an error occurred — the exact value returned indicates the nature of the error.

The problem with this approach is that people generally don’t check all the possible error returns. It’s too much trouble. And if you were to check all the possible error returns, pretty soon you wouldn’t see the “real code” because of all those error paths that are almost never executed.

Finally, you can embed just so much information in a single return value. For example, the factorial() function could return a −1 for “negative argument” (the factorial of a negative number is not defined) and a −2 for “argument too large” (factorials get large very quickly — factorial(100) is well beyond the ...

Get Beginning Programming with C++ For Dummies, 2nd Edition 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.