类中的异常处理
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()
相关文章:
- 为什么我应该在异常处理中使用std::cerr而不是std::cout
- 当我使用 C++ 中的 C# dll 来使用 Selenium 时,存在异常处理问题
- Firebase C++VS2018 SDL2-在Firebase::app::create(..)上执行异常处理
- 使用 stoi 功能进行异常处理
- 子系统中的异常处理:本机
- 与异常处理程序中的操作员<<不匹配
- 数组 C++ 上的异常处理程序
- 异常处理:如果用户输入不是三个特定字符之一
- C++ 异常处理错误输出
- 视觉 std::矢量无异常:警告 C4530:使用了C++异常处理程序,但未启用展开语义.指定 /EHsc
- C++交换机状态异常处理
- 在字符串类上的成员函数和out_of_range异常处理
- 奇怪的消息 (_Base_bitset::_M_do_to_ulong) 从溢出异常处理程序中打印出来
- 执行视觉工作室异常处理模式
- 为什么隐式转换在异常处理中从派生到基?
- C++执行期间的类成员函数错误/异常处理
- C++ 中未处理的异常处理程序
- 用户定义的异常处理
- C :ScopeGuard vs返回支票和异常处理
- 异常处理期间的类型解析