Выбрать главу

The exception specification reuses the keyword throw, followed by a parenthesized list of all the types of potential exceptions that the function can throw. Your function declaration might look like this:.

void f() throw(toobig, toosmall, divzero);

As far as exceptions are concerned, the traditional function declaration

void f();

means that any type of exception can be thrown from the function. If you say

void f() throw();

no exceptions whatsoever will be thrown from the function (so you’d better be sure that no functions farther down in the call chain let any exceptions propagate up!).

For good coding policy, good documentation, and ease-of-use for the function caller, always consider using exception specifications when you write functions that throw exceptions. (Exceptions to this guideline are discussed later in this chapter.)

The unexpected( ) function

If your exception specification claims you’re going to throw a certain set of exceptions and then you throw something that isn’t in that set, what’s the penalty? The special function unexpected( ) is called when you throw something other than what appears in the exception specification. Should this unfortunate situation occur, the default implementation of unexpected calls the terminate( ) function mentioned earlier in this chapter.

The set_unexpected( ) function

Like terminate( ), the unexpected( ) mechanism allows you to install your own function to respond to unexpected exceptions. You do so with a function called set_unexpected( ), which, like set_terminate( ), takes the address of a function with no arguments and void return value. Also, because it returns the previous value of the unexpected( ) pointer, you can save it and restore it later. To use set_unexpected( ), include the header file <exception>. Here’s an example that shows a simple use of the features discussed so far in this section:.

//: C01:Unexpected.cpp

// Exception specifications & unexpected()

//{-msc} Doesn’t terminate properly

#include <exception>

#include <iostream>

#include <cstdlib>

using namespace std;

class Up {};

class Fit {};

void g();

void f(int i) throw (Up, Fit) {

  switch(i) {

    case 1: throw Up();

    case 2: throw Fit();

  }

  g();

}

// void g() {} // Version 1

void g() { throw 47; } // Version 2

void my_unexpected() {

  cout << "unexpected exception thrown" << endl;

  exit(0);

}

int main() {

  set_unexpected(my_unexpected);

  // (ignores return value)

  for(int i = 1; i <=3; i++)

    try {

      f(i);

    } catch(Up) {

      cout << "Up caught" << endl;

    } catch(Fit) {

      cout << "Fit caught" << endl;

    }

} ///:~

The classes Up and Fit are created solely to throw as exceptions. Often exception classes will be small, but they can certainly hold additional information so that the handlers can query for it.

The f( ) function promises in its exception specification to throw only exceptions of type Up and Fit, and from looking at the function definition, this seems plausible. Version one of g( ), called by f( ), doesn’t throw any exceptions, so this is true. But if someone changes g( ) so that it throws a different type of exception (like the second version in this example, which throws an int), the exception specification for f( ) is violated.

The my_unexpected( ) function has no arguments or return value, following the proper form for a custom unexpected( ) function. It simply displays a message so that you can see that it was called, and then exits the program (exit(0) is used here so that the book’s make process is not aborted). Your new unexpected( ) function should not have a return statement.

In main( ), the try block is within a for loop, so all the possibilities are exercised. In this way, you can achieve something like resumption. Nest the try block inside a for, while, do, or if and cause any exceptions to attempt to repair the problem; then attempt the try block again.

Only the Up and Fit exceptions are caught because those are the only exceptions that the programmer of f( ) said would be thrown. Version two of g( ) causes my_unexpected( ) to be called because f( ) then throws an int.

In the call to set_unexpected( ), the return value is ignored, but it can also be saved in a pointer to function and be restored later, as we did in the set_terminate( ) example earlier in this chapter.

A typical unexpected handler logs the error and terminates the program by calling exit( ). It can, however, throw another exception (or re-throw the same exception) or call abort( ). If it throws an exception of a type allowed by the function whose specification was originally violated, the search resumes at the call of the function with this exception specification. (This behavior is unique to unexpected( ).)

If the exception thrown from your unexpected handler is not allowed by the original function’s specification, one of the following occurs:

1.       If std::bad_exception (defined in <exception>) was in the function’s exception specification, the exception thrown from the unexpected handler is replaced with a std::bad_exception object, and the search resumes from the function as before.

2.      If the original function’s specification did not include std::bad_exception, terminate( ) is called.

The following program illustrates this behavior.

//: C01:BadException.cpp