O'Reilly logo

C++ For Dummies, 7th Edition by Stephen R. Davis

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 24

Handling Errors — Exceptions

In This Chapter

arrow Introducing an exceptional way of handling program errors

arrow Finding what’s wrong with good ol’ error returns

arrow Examining throwing and catching exceptions

arrow Packing more heat into that throw

I know that it’s hard to accept, but occasionally functions don’t work properly — not even mine. The traditional means of reporting failure is to return some indication to the caller. C++ includes a mechanism for capturing and handling errors called exceptions. The handling of error conditions with exceptions is the subject of this chapter.

The exception mechanism is based on the keywords try, catch, and throw (that’s right, more variable names that you can’t use). In outline, it works like this: A function trys to get through a piece of code. If the code detects a problem, it throws an error indication that the calling function must catch.

The following code snippet demonstrates how that works in 1s and 0s:

  //  FactorialException - demonstrate exceptions using//                       a factorial function//#include <cstdio>#include <cstdlib> ...

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