Chapter 24. Handling Errors — Exceptions

In This Chapter

  • Introducing an exceptional way of handling program errors

  • Finding what's wrong with good ol' error returns

  • Examining throwing and catching exceptions

  • 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 new, improved mechanism for capturing and handling errors called exceptions. An exception is defined as "a case in which a rule or principle does not apply." Exception is also defined as an objection to something. Either definition works: An exception is an unexpected (and presumably objectionable) condition that occurs during the execution of the program.

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>
#include <iostream>
using namespace std;

// factorial - compute factorial
int factorial(int n) throw (string)
// you can't handle negative values of n; // better check for that condition first if (n < 0) { throw string("Argument ...

Get C++ For Dummies®, 6th Edition now with the O’Reilly learning platform.

O’Reilly members experience live online training, plus books, videos, and digital content from nearly 200 publishers.