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

Chapter 15

Why Exceptions in C++ Are a Bad Thing

Despite the advantages of exceptions in general, their specific implementation in C++ makes them undesirable to some programmers. The first problem is performance: the language features added to support exceptions slow down all programs, even those that don’t use exceptions. However, unless you’re writing high-performance or systems-level software, you should be okay. Chapter 17 discusses this issue in more detail.

A second problem is that exception support in C++ is not an integral part of the language the same way it is in other languages, such as Java. For example, in Java a function that does not specify a list of possible exceptions that it can throw is not allowed to throw any exceptions. That makes sense. In C++, it is just the opposite: a function that does not specify a list of exceptions can throw any exception it wants! Additionally, the exception list is not enforced at compile time in C++, meaning that the exception list of a function can be violated at run time. These, and other, inconsistencies make exceptions in C++ harder to use correctly than they should be, intimidating some programmers.

Finally, the exception mechanism presents problems for dynamically allocated memory and resource cleanup. When you program with exceptions, it is difficult to ensure that you perform proper cleanup. This issue is explored below.

Our Recommendation

Despite the downsides, we recommend exceptions as a useful mechanism for error handling. We feel that the structure and error-handling formalization that exceptions provide outweigh the less desirable aspects. Thus, the remainder of this chapter focuses on exceptions. Even if you do not plan to use exceptions in your programs, you should skim this chapter to gain a familiarity with some of the common error-handling issues in C++ programming.

Exception Mechanics

Exceptional situations arise frequently in the area of file input and output. Below is a simple function to open a file, read a list of integers from the file, and store the integers in the supplied vector data structure. Recall from Chapter 4 that the vector is a dynamic array. You can add elements to it using the push_back() method, and access them with array notation.

#include <fstream> #include <iostream> #include <vector> #include <string> using namespace std;

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

{

ifstream istr; int temp;

istr.open(fileName.c_str());

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

404

Handling Errors

dest.push_back(temp);

}

}

You might use readIntegerFile() like this:

int main(int argc, char** argv)

{

vector<int> myInts;

const string fileName = “IntegerFile.txt”;

readIntegerFile(fileName, myInts);

for (size_t i = 0; i < myInts.size(); i++) { cout << myInts[i] << “ “;

}

cout << endl;

return (0);

}

The lack of error handling in these functions should jump out at you. The rest of this section shows you how to add error handling with exceptions.

Throwing and Catching Exceptions

The most likely problem to occur in the readIntegerFile() function is for the file open to fail. That’s a perfect situation for throwing an exception. The syntax looks like this:

#include <fstream> #include <iostream> #include <vector> #include <string> #include <exception> using namespace std;

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

{

ifstream istr; int temp;

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

// We failed to open the file: throw an exception.

throw exception();

}

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

dest.push_back(temp);

}

}

405

Chapter 15

throw is a keyword in C++, and is the only way to throw an exception. C++ provides a class named exception, declared in the <exception> header file. The exception() part of the throw line means that you are constructing a new object of type exception to throw.

If the function fails to open the file and executes the throw exception(); line, the rest of the function is skipped, and control transitions to the nearest exception handler.

Throwing exceptions in your code is most useful when you also write code that handles them. Here is a main() function that handles the exception thrown in readIntegerFile():

int main(int argc, char** argv)

{

vector<int> myInts;

const string fileName = “IntegerFile.txt”;

try {

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

cerr << “Unable to open file “ << fileName << endl;

exit (1);

}

for (size_t i = 0; i < myInts.size(); i++) { cout << myInts[i] << “ “;

}

cout << endl;

return (0);

}

Exception handling is a way to “try” a block of code, with another block of code designated to react to any problems that might occur. In this particular case, the catch statement reacts to any exception of type exception that was thrown within the try block by printing an error message and exiting. If the try block finishes without throwing an exception, the catch block is skipped. You can think of try/ catch blocks as glorified if statements. If an exception is thrown in the try block, execute the catch block. Otherwise, skip it.

Although by default streams do not throw exceptions, you can tell the streams to throw exceptions for error conditions by calling their exceptions() method. However, no less a luminary than Bjarne Stroustrup (who created C++) recommends against this approach. In The C++ Programming Language, third edition, he says “ . . . I prefer to deal with the stream state directly. What can be handled with local control structures within a function is rarely improved by the use of exceptions.” This book follows his guidelines in that regard.

Exception Types

You can throw an exception of any type. The preceding example throws an object of type exception, but exceptions do not need to be objects. You could throw a simple int like this:

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

{

// Code omitted istr.open(fileName.c_str());

406

Handling Errors

if (istr.fail()) {

// We failed to open the file: throw an exception. throw 5;

}

// Code omitted

}

You would then need to change the catch statement as well:

int main(int argc, char** argv)

{

//code omitted try {

readIntegerFile(fileName, myInts); } catch (int e) {

cerr << “Unable to open file “ << fileName << endl; exit (1);

}

//Code omitted

}

Alternatively, you could throw a char* C-style string. This technique is sometimes useful because the string can contain information about the exception.

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

{

// Code omitted istr.open(fileName.c_str()); if (istr.fail()) {

// We failed to open the file: throw an exception. throw “Unable to open file”;

}

// Code omitted

}

When you catch the char* exception, you can print the result:

int main(int argc, char** argv)

{

//Code omitted try {

readIntegerFile(fileName, myInts); } catch (const char* e) {

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

}

//Code omitted

}

However, you should generally throw objects as exceptions for two reasons:

Objects convey information simply by their class name.

Objects can store information, such as strings, that describe the exceptions.

407