| I l@ve RuBoard |
|
7.3 Exercise 7.3Add a pair of exceptions to the Stack class hierarchy of Exercise 6.2 to handle the cases of attempting to pop a stack that is empty and attempting to push a stack that is full. Show the modified pop() and push() member functions. We'll define a PopOnEmpty and a PushOnFull pair of exception classes to be thrown, respectively, in the pop() and push() Stack member functions. These classes no longer need to return a success or failure value:
void pop( elemType &elem )
{
if ( empty() )
throw PopOnEmpty();
elem = _stack[ --_top ];
_stack.pop_back();
}
void push( const elemType &elem ){
if ( ! full() ){
_stack.push_back( elem );
++_top;
return;
}
throw PushOnFull();
}
To allow these two Stack class exceptions to be caught in components that do not explicitly know about PopOnEmpty and PushOnFull exception classes, the class exceptions are made part of a StackException hierarchy that is derived from the standard library logic_error class. The logic_error class is derived from exception, which is the root abstract base class of the standard library exception class hierarchy. This hierarchy declares a virtual function what() that returns a const char* identifying the exception that has been caught.
class StackException : public logic_error {
public:
StackException( const char *what ) : _what( what ){}
const char *what() const { return _what.c_str(); }
protected:
string _what;
};
class PopOnEmpty : public StackException {
public:
PopOnEmpty() : StackException( "Pop on Empty Stack" ){}
};
class PushOnFull : public StackException {
public:
PushOnFull() : StackException( "Push on Full Stack" ){}
};
Each of the following catch clauses handles an exception of type PushOnFull:
catch( const PushOnFull &pof )
{ log( pof.what() ); return; }
catch( const StackException &stke )
{ log( stke.what() ); return; }
catch( const logic_error &lge )
{ log( lge.what() ); return; }
catch( const exception &ex )
{ log( ex.what() ); return; }
|
| I l@ve RuBoard |
|