简体   繁体   中英

c++:Working with throw,try and catch

I am just trying to get throw, try and catch to work. Here is my header file for my stack and I place my throw in "/* */" to ignore it for now. http://codepad.org/0Pm2Hy6u

It is for when I pop and push so throw out error if it is full or empty with the exception. I am all new at these.

In my book it sets FullStack and EmptyStack as so... Class FullStack{}; (so empty class) and same for EmptyStack.

Could some one perhaps help me figure this out.

Here is a simple main: http://codepad.org/dbk4Ke6C

How can I get try and catch to work. ex) When calling stack.Push(item) and it is full I could catch the error and display it

Here is fixed a version as a single file:

See it live here: https://ideone.com/95gMc

In short:

  • you needed to define the exeption classes before you can throw them. Include them in the header file for StackType
  • do NOT use (global) using namespace in header files! You will make life miserable for users of your class that try to avoid clashes between namespaces
  • you needed to push 1 more value onto the stack

I minimized the comments because it was a bit lengthy to quote inline (and comments should be pulling their weight, IMO)

May I suggest:

  • derive from a common stack exception base class (also suggests a more consistent naming convention for Exception classes): Edit fixed this up somewhat. For rationale, see this background article

      #include <stdexcept> struct StackException : virtual std::exception { protected: StackException() {} }; struct StackFullException : StackException { char const* what() const throw() { return "StackFullException"; } }; struct StackEmptyException : StackException { char const* what() const throw() { return "StackEmptyException"; } }; 

    that way you can always catch any StackException& (by reference ) and handle either stack full/empty in one go

  • to handle the exception, use something like this:

     int main() { try { // .... } catch (const StackException& e) { std::cerr << "oops, a stack error occured: " << e.what() << std::endl; } } 

Edit example edited to demonstrate the enhanced exception types and a sample handler:

//Purpose: Header file for StackType. Containing all declerations and prototypes
#include <stdexcept>

struct StackException : virtual std::exception 
{  
    protected: StackException() {}
};
struct StackFullException : StackException 
{
    char const* what() const throw() { return "StackFullException"; }
};
struct StackEmptyException : StackException
{
    char const* what() const throw() { return "StackEmptyException"; }
};


template <class itemType>
class StackType
{
public:
    StackType   (int max);
    StackType   ();
    bool IsEmpty() const;
    bool IsFull () const;
    void Push   (itemType newItem);
    void Pop    ();
    itemType Top() const;
    ~StackType  (); // Destructor

private:
    int top;        // key:top of the stack
    int maxStack;   // max number of stack items
    itemType* list; // pointer to dynamically allocated memory
};

/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
/*Implementation (StackStype.cpp)
StackType prototype functions*/

template <class itemType>
StackType<itemType>::StackType(int max)
{
    maxStack = max;
    top = -1;
    list = new itemType[maxStack];
}

template <class itemType>
StackType<itemType>::StackType()
{
    maxStack = 200;
    top = -1;
    list = new itemType[maxStack];
}

template <class itemType>
bool StackType<itemType>::IsEmpty() const
{
    return(top == -1);
}

template <class itemType>
bool StackType<itemType>::IsFull() const
{
    return(top == maxStack - 1);
}

template <class itemType>
void StackType<itemType>::Push(itemType newItem)
{
    if(IsFull())
    {
        throw StackFullException();
    }
    top++;
    list[top] = newItem;
}

template <class itemType>
void StackType<itemType>::Pop()
{
    if(IsEmpty())
    {
        throw StackEmptyException();
    }
    top--;
}

template <class itemType>
itemType StackType<itemType>::Top() const
{
    if(IsEmpty())
    {
        throw StackEmptyException();
    }
    return list[top];
}

template <class itemType>
StackType<itemType>::~StackType()
{
    delete [] list;
}

///////////////////////////////////////
// sample main.cpp

#include <iostream>
int main(void)
{
    try
    {
        StackType<int> stack(5);
        stack.Push(5);
        stack.Push(2);
        stack.Push(3);
        stack.Push(4);
        stack.Push(1);//<-----Still Ok!
        stack.Push(0);//<-----throw FullStack
    } catch (const StackException& e)
    {
        std::cerr << "Received a StackException: what()? " << e.what() << std::endl;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM