类中的异常处理

Exception handling in a class C++

本文关键字:异常处理      更新时间:2023-10-16

我正在学习c++中的数据结构和算法,目前我面临一个问题。我正在使用数组编写堆栈类,书中建议我在函数声明中使用异常规范。在我的情况下,我有StackEmptyException和StackFullException类派生自RuntimeException类,书中说,我不应该试图捕捉这个异常在函数体,但每当我试图运行我的程序强制一个异常,它无法开始说"未处理的异常"。我想知道这个问题是从哪里来的,因为书中并没有真正解释它,只是提了一下,所以我很感激任何相关的答案。下面是我的代码:

class RuntimeException {
private:
    string errMsg;
public:
    RuntimeException(const string& err) { errMsg = err; }
    string getMessage() const { return errMsg; }
};
inline ostream& operator<<(ostream& out, const RuntimeException& e){
    return out << e.getMessage();
}
class StackEmptyException : public RuntimeException {
public:
    StackEmptyException(const string& err) : RuntimeException(err) {}
};
class StackFullException : public RuntimeException {
public:
    StackFullException(const string& err) : RuntimeException(err) {}
};
template <typename Object>
class ArrayStack {
private:
    enum { CAPACITY = 1000 };
    int capacity;
    Object* S;
    int t;
public:
    ArrayStack(int cap = CAPACITY) {
        capacity = cap;
        S = new Object[capacity];
        t = -1;
    }
    int size() const { return t + 1; }
    bool isEmpty() const { return (t < 0); }
    // Passing the object by reference so that we could
    // edit its value    e.g. stack.top() = 10; would be valid
    Object& top() throw(StackEmptyException) { 
        if (isEmpty())
            throw StackEmptyException("Access to empty stack");
        return S[t];
    }
    void push(const Object& elem) throw(StackFullException) {
        if (size() == capacity)
            throw StackFullException("Stack overflow");
        S[++t] = elem;
    }
    // Not passing by reference, because we remove the last element
    // from the stack, thus we can not change its value 
    Object pop() throw(StackEmptyException) {
        if (isEmpty())
            throw StackEmptyException("Access to empty stack");
        return S[t--];
    }
    ArrayStack(const ArrayStack& st);               // Copy constructor
    ArrayStack& operator=(const ArrayStack& st);    // Assignment operator constructor
    ~ArrayStack() { delete[] S; }                   // Destructor
};

我认为你的书上说你不应该总是使用try/catch来捕获这个的原因是因为你应该首先自己做边界检查。因此,在你使用pop()之前,首先检查是否为isEmpty()