Exercise

    Exercise P17.1 One argument used to justify the fact that the stack data structure in the standard library does not throw an exception is that it is easy to add these facilities. Create a class SafeStack that implements a stack of strings. Use an instance of stack<string. to hold the underlying values, and implement the same interface as that data type. However, your class should throw an exception if an attempt is made to remove a value from an empty stack.

    Your SafeStack class provides a service for the programmers in your company. If the other programmers need a stack which is safe, they will include your SafeStack header and link in your SafeStack.cpp file.
    Notice, your SafeStack should throw an exception but it is the other programmers in your group who need to catch the exception. They are the ones who are delivering systems to users and they have to decide what messages to display to the users.
    The code that you use for testing might look something like this:

    int main()
    {
    SafeStack s;
    try
    {
    . . .
    . . .
    while ( . . . )
    {
    cout << s.top() << “n”;
    s.pop();
    }
    }
    catch ( logic_error &e)
    {
    cout << e.what() << endl;
    }
    system(“pause”); // needed in Visual Studio
    return 0;
    }

    The stack class itself can’t catch the exception, because the developer of the stack class doesn’t know who the users are and what kind of message they are expecting.

                                                                                                                                      Order Now