Добавил:
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
Professional C++ [eng].pdf
Скачиваний:
1715
Добавлен:
16.08.2013
Размер:
11.09 Mб
Скачать

Chapter 15

Are Throw Lists Useful?

Given the opportunity to specify the behavior of a function in its signature, it seems wasteful not to take advantage of it. The exceptions thrown from a particular function are an important part of its interface, and should be documented as well as possible.

Unfortunately, most of the C++ code in use today, including the Standard Library, does not follow this advice. That makes it difficult for you to determine which exceptions can be thrown when you use this code. Additionally, it is impossible to specify the exception characteristics of templatized functions and methods. When you don’t even know what types will be used to instantiate the template, you have no way to determine the exceptions that methods of those types can throw. As a final problem, the throw list syntax and enforcement is somewhat obscure.

Thus, we leave the decision up to you.

Exceptions and Polymorphism

As described above, you can actually throw any type of exception. However, classes are the most useful types of exceptions. In fact, exception classes are usually written in a hierarchy, so that you can employ polymorphism when you catch the exceptions.

The Standard Exception Hierarchy

You’ve already seen several exceptions from the C++ standard exception hierarchy: exception, runtime_error, and invalid_argument. Figure 15-3 shows the complete hierarchy:

 

 

 

 

 

 

 

 

 

 

exception

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

bad_alloc

 

 

 

 

bad_cast

 

 

 

 

 

bad_exception

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

logic_error

 

 

 

ios_base::failure

 

 

runtime_error

 

bad_typeid

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

domain_error

 

 

 

 

invalid_argument

 

 

length_error

 

range_error

 

 

overflow_error

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

out_of_range

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

underflow_error

Figure 15-3

All of the exceptions thrown by the C++ Standard Library are objects of classes in this hierarchy. Each class in the hierarchy supports a what() method that returns a char* string describing the exception. You can use this string in an error message.

416

Handling Errors

All the exception classes except for the base exception require you to set in the constructor the string that will be returned by what(). That’s why you have to specify a string in the constructors for runtime_ error and invalid_argument. Now that you know what the strings are used for, you can make them more useful. Here is an example where the string is used to pass the full error message back to the caller:

void readIntegerFile(const string& fileName, vector<int>& dest) throw (invalid_argument, runtime_error)

{

ifstream istr; int temp;

istr.open(fileName.c_str()); if (istr.fail()) {

// We failed to open the file: throw an exception. string error = “Unable to open file “ + fileName;

throw invalid_argument(error);

}

// Read the integers one by one and add them to the vector. while (istr >> temp) {

dest.push_back(temp);

}

if (istr.eof()) {

//We reached the end-of-file. istr.close();

}else {

//Some other error. Throw an exception. istr.close();

string error = “Unable to read file “ + fileName; throw runtime_error(error);

}

}

int main(int argc, char** argv)

{

//Code omitted try {

readIntegerFile(fileName, myInts); } catch (const invalid_argument& e) {

cerr << e.what() << endl; exit (1);

} catch (const runtime_error& e) { cerr << e.what() << endl; exit (1);

}

//Code omitted

}

Catching Exceptions in a Class Hierarchy

The most exciting feature of exception hierarchies is that you can catch exceptions polymorphically. For example, if you look at the two catch statements in main() following the call to readIntegerFile(), you can see that they are identical except for the exception class that they handle. Conveniently,

417

Chapter 15

invalid_argument and runtime_error are both subclasses of exception, so you can replace the two catch statements with a single catch statement for class exception:

int main(int argc, char** argv)

{

//Code omitted try {

readIntegerFile(fileName, myInts); } catch (const exception& e) {

cerr << e.what() << endl; exit (1);

}

//Code omitted

}

The catch statement for an exception reference matches any subclasses of exception, including both invalid_argument and runtime_error. Note that the higher in the exception hierarchy that you catch exceptions, the less specific is your error handling. You should generally catch exceptions at as specific a level as possible.

When you catch exceptions polymorphically, make sure to catch them by reference. If you catch exceptions by value, you can encounter slicing, in which case you lose information from the object. See Chapter 10 for details on slicing.

The polymorphic matching rules work on a “first come, first served” basic. C++ attempts to match the exception against each catch statement in order. The exception matches a catch statement if it is an object of that class or an object of a subclass of the class, even if a more exact match comes in a later catch statement. For example, suppose that you want to catch invalid_argument from readIntegerFile() explicitly, but leave the generic exception match for any other exceptions. The correct way to do so is like this:

try {

readIntegerFile(fileName, myInts);

}catch (const invalid_argument& e) { // List the exception subclass first.

//Take some special action for invalid filenames.

}catch (const exception& e) { // Now list exception

cerr << e.what() << endl; exit (1);

}

The first catch statement catches invalid_argument exceptions, and the second catches any other exceptions. However, if you reverse the order of the catch statements, you don’t get the same result:

try {

readIntegerFile(fileName, myInts);

}catch (const exception& e) { // BUG: catching superclass first! cerr << e.what() << endl;

exit (1);

}catch (const invalid_argument& e) {

// Take some special action for invalid filenames.

}

418

Handling Errors

With this order, any exception of a class that subclasses exception is caught by the first catch statement; the second will never be reached. Some compilers issue a warning in this case, but you shouldn’t count on it.

Writing Your Own Exception Classes

There are two advantages to writing your own exception classes.

1.The number of exceptions in the C++ Standard Library is limited. Instead of using an exception class with a generic name, such as runtime_exception, you can create classes with names that are more meaningful for the particular errors in your program.

2.You can add your own information to these exceptions. The exceptions in the standard hierarchy allow you to set only an error string. You might want to pass different information in the exception.

We recommend that all the exception classes that you write inherit directly or indirectly from the standard exception class. If everyone on your project follows that rule, you know that every exception in the program will be a subclass of exception (assuming that you aren’t using third-party libraries that break this rule). This guideline makes exception handling via polymorphism significantly easier.

For example, invalid_argument and runtime_error don’t capture very well the file opening and reading errors in readIntegerFile(). You can define your own error hierarchy for file errors, starting with a generic FileError class:

class FileError : public runtime_error

{

public:

FileError(const string& fileIn) : runtime_error(“”), mFile(fileIn) {} virtual ~FileError() throw() {}

virtual const char* what() const throw() { return mMsg.c_str(); } string getFileName() { return mFile; }

protected:

string mFile, mMsg;

};

As a good programming citizen, you should make FileError a part of the standard exception hierarchy. It seems appropriate to integrate it as a child of runtime_error. When you write a subclass of runtime_error (or any other exception in the standard hierarchy), you need to override two methods: what() and the destructor.

what() has the signature shown and is supposed to return a char* string that is valid until the object is destroyed. In the case of FileError, this string comes from the mMsg data member, which is set to “” in the constructor. Subclasses of FileError must set this mMsg string to something different if they want a different message.

You must override the destructor in order to specify the empty throw list. The compiler-generated destructor has no throw list, which won’t compile, because runtime_error specifies an empty throw list.

The generic FileError class also contains a filename and an accessor for that filename.

419

Chapter 15

The first exceptional situation in readIntegerFile() occurs if the file cannot be opened. Thus, you might want to write a FileOpenError subclass of FileError:

class FileOpenError : public FileError

{

public:

FileOpenError(const string& fileNameIn); virtual ~FileOpenError() throw() {}

};

FileOpenError::FileOpenError(const string& fileNameIn) : FileError(fileNameIn)

{

mMsg = “Unable to open “ + fileNameIn;

}

The FileOpenError changes the mMsg string to represent the file-opening error.

The second exceptional situation in readIntegerFile() occurs if the file cannot be read properly. It might be useful for this exception to contain the line number of the error in the file, as well as the filename and the error message string returned from what(). Here is a FileReadError subclass of FileError:

class FileReadError : public FileError

{

public:

FileReadError(const string& fileNameIn, int lineNumIn); virtual ~FileReadError() throw() {}

int getLineNum() { return mLineNum; }

protected:

int mLineNum;

};

FileReadError::FileReadError(const string& fileNameIn, int lineNumIn) : FileError(fileNameIn), mLineNum(lineNumIn)

{

ostringstream ostr;

ostr << “Error reading “ << fileNameIn << “ at line “ << lineNumIn; mMsg = ostr.str();

}

Of course, in order to set the line number properly, you need to modify your readIntegerFile() function to track the number of lines read instead of just reading integers directly. Here is a new readIntegerFile() function that uses the new exceptions:

void readIntegerFile(const string& fileName, vector<int>& dest) throw (FileOpenError, FileReadError)

{

ifstream istr; int temp;

char line[1024]; // Assume that no line is longer than 1024 characters.

int lineNumber = 0;

istr.open(fileName.c_str()); if (istr.fail()) {

420

Handling Errors

// We failed to open the file: throw an exception. throw FileOpenError(fileName);

}

while (!istr.eof()) {

//Read one line from the file. istr.getline(line, 1024); lineNumber++;

//Create a string stream out of the line. istringstream lineStream(line);

//Read the integers one by one and add them to the vector. while (lineStream >> temp) {

dest.push_back(temp);

}

if (!lineStream.eof()) {

// Some other error. Close the file and throw an exception. istr.close();

throw FileReadError(fileName, lineNumber);

}

}

istr.close();

}

Now code that calls readIntegerFile() can use polymorphism to catch exceptions of type FileError like this:

try {

readIntegerFile(fileName, myInts); } catch (const FileError& e) {

cerr << e.what() << endl; exit (1);

}

There is one trick to writing classes whose objects will be used as exceptions. When a piece of code throws an exception, the object or value thrown is copied. That is, a new object is constructed from the old object using the copy constructor. It must be copied because the original could go out of scope (and be destroyed and have its memory reclaimed) before the exception is caught, higher up in the stack. Thus, if you write a class whose objects will be thrown as exceptions, you must make those objects copyable. This means that if you have dynamically allocated memory, you must write a destructor, copy constructor, and assignment operator, as described in Chapter 9.

Objects thrown as exceptions are always copied by value at least once.

It is possible for exceptions to be copied more than once, but only if you catch the exception by value instead of by reference.

Catch exception objects by reference to avoid unnecessary copying.

421