Chapter 32. I Take Exception!
In This Chapter
Introducing the exception mechanism for handling program errors
Examining the mechanism in detail
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 of the possible error returns. It's too much trouble. And if you were to check all of the possible error returns, pretty soon you wouldn't see the "real code" because of all the 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 range of an int
). But if the program were to return a −2, wouldn't you like to know the value of that "too large argument"? There's no easy way to embed that information in the return.
The fathers (and mothers) of C++ decided that the language needed a better way of handling errors, so they invented the exception ...
Get Beginning Programming with C++ For Dummies® 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.