//: C01:InitExcept.cpp
// Handles exceptions from subobjects
//{-bor}
#include
using namespace std;
class Base {
int i;
public:
class BaseExcept {};
Base(int i) : i(i) {
throw BaseExcept();
}
};
class Derived : public Base {
public:
class DerivedExcept {
const char* msg;
public:
DerivedExcept(const char* msg) : msg(msg) {}
const char* what() const {
return msg;
}
};
Derived(int j)
try
: Base(j) {
// Constructor body
cout << "This won't print\n";
}
catch (BaseExcept&) {
throw DerivedExcept("Base subobject threw");;
}
};
int main() {
try {
Derived d(3);
}
catch (Derived::DerivedExcept& d) {
cout << d.what() << endl; // "Base subobject threw"
}
} ///:~
Notice that the initializer list in the constructor for Derivedgoes after the trykeyword but before the constructor body. If an exception does indeed occur, the contained object is not constructed, so it makes no sense to return to the code that created it. For this reason, the only sensible thing to do is to throw an exception in the function-level catchclause .
Although it is not terribly useful, C++ also allows function-level tryblocks for any function, as the following example illustrates:
//: C01:FunctionTryBlock.cpp
// Function-level try blocks
//{-bor}
#include
using namespace std;
int main() try {
throw "main";
} catch(const char* msg) {
cout << msg << endl;
return 1;
} ///:~
In this case, the catchblock can return in the same manner that the function body normally returns. Using this type of function-level tryblock isn’t much different from inserting a try-catcharound the code inside of the function body .
The set of exceptions used with the Standard C++ library is also available for your use. Generally it’s easier and faster to start with a standard exception class than to try to define your own. If the standard class doesn’t do exactly what you need, you can derive from it .
All standard exception classes derive ultimately from the class exception, defined in the header . The two main derived classes are logic_errorand runtime_error, which are found in (which itself includes ). The class logic_errorrepresents errors in programming logic, such as passing an invalid argument. Runtime errors are those that occur as the result of unforeseen forces such as hardware failure or memory exhaustion. Both runtime_errorand logic_errorprovide a constructor that takes a std::stringargument so that you can store a message in the exception object and extract it later with exception::what( ), as the following program illustrates .
//: C01:StdExcept.cpp
// Derives an exception class from std::runtime_error
#include
#include
using namespace std;
class MyError : public runtime_error {
public:
MyError(const string& msg = "") : runtime_error(msg) {}
};
int main() {
try {
throw MyError("my message");
}
catch (MyError& x) {
cout << x.what() << endl;
}
} ///:~
Although the runtime_errorconstructor passes the message up to its std::exceptionsubobject to hold, std::exceptiondoes not provide a constructor that takes a std::stringargument. Therefore, you usually want to derive your exception classes from either runtime_erroror logic_error(or one of their derivatives), and not from std::exception .
The following tables describe the standard exception classes.
exception |
The base class for all the exceptions thrown by the C++ standard library. You can ask what( )and retrieve the optional string with which the exception was initialized. |
logic_error |
Derived from exception. Reports program logic errors, which could presumably be detected by inspection. |
runtime_error |
Derived from exception. Reports runtime errors, which can presumably be detected only when the program executes. |
The iostream exception class ios::failureis also derived from exception, but it has no further subclasses .
You can use the classes in both of the following tables as they are, or you can use them as base classes from which to derive your own more specific types of exceptions .
Exception classes derived from logic_error |
domain_error |
Reports violations of a precondition. |
invalid_argument |
Indicates an invalid argument to the function from which it’s thrown. |
length_error |
Indicates an attempt to produce an object whose length is greater than or equal to npos(the largest representable value of type size_t). |
Out_of_range |
Reports an out-of-range argument. |
Bad_cast |
Thrown for executing an invalid dynamic_castexpression in runtime type identification (see Chapter 8). |
bad_typeid |
Reports a null pointer pin an expression typeid(*p). (Again, a runtime type identification feature in Chapter 8). |
Exception classes derived from runtime_error |
range_error |
Reports violation of a postcondition. |
overflow_error |
Reports an arithmetic overflow. |
bad_alloc |
Reports a failure to allocate storage. |
You’re not required to inform the people using your function what exceptions you might throw. Failure to do so can be considered uncivilized, however, because it means that users cannot be sure what code to write to catch all potential exceptions. Of course, if they have your source code, they can hunt through and look for throwstatements, but often a library doesn’t come with sources. Good documentation can help alleviate this problem, but how many software projects are well documented? C++ provides syntax that allows you to tell the user what exceptions this function throws, so the user can handle them. This is the optional exception specification , which adorns a function’s declaration, appearing after the argument list .
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.)
Читать дальше