怎么用
这是一段 用原始数组实现的栈 模板。里面用throw处理了一些可能出现的异常。
// 使用原始数组实现
template <typename T>
class Stack_arr
{
public:
Stack_arr() : TopIndex(-1) {}
void push(const T& element)
{
// 因为原始数组是静态的, 所以得先判断栈还有没有空间
if (TopIndex >= MaxSize - 1)
{
throw std::overflow_error("栈已满!");
}
Elements[++TopIndex] = element;
}
void pop()
{
if (TopIndex < 0)
{
throw std::underflow_error("空栈,不可弹出!");
}
--TopIndex;
}
T& top()
{
if (TopIndex < 0)
{
throw std::out_of_range("空栈,没有元素!");
}
return Elements[TopIndex];
}
bool empty() const
{
return TopIndex < 0;
}
int size() const
{
return TopIndex + 1;
}
private:
static const int MaxSize = 3; // 因为原始数组是静态的,所以要设置栈的最大容量
T Elements[MaxSize]; // 栈的容器:数组
int TopIndex = -1; // 栈顶索引
};
在main函数里使用这个栈(先不触发异常):
int main()
{
Stack_arr<int> stack;
try
{
//stack.pop(); // 异常
// 压入元素
stack.push(10);
stack.push(20);
stack.push(30);
//stack.push(40); // 异常
std::cout << "栈的大小: " << stack.size() << std::endl;
std::cout << "栈顶元素: " << stack.top() << std::endl << std::endl;
// 弹出所有元素
while (!stack.empty())
{
std::cout << "榨取ing" << std::endl;
stack.pop();
}
std::cout << std::endl;
//stack.pop(); // 异常
// 检查栈是否为空
if (stack.empty())
{
std::cout << "已经一滴都没有惹" << std::endl;
}
}
catch (const std::overflow_error& e)
{
std::cerr << "捕获异常: " << e.what() << std::endl;
}
catch (const std::underflow_error& e)
{
std::cerr << "捕获异常: " << e.what() << std::endl;
}
return 0;
}
- 如果没有用try-catch来捕获异常,那么这时throw的作用是:
- 在异常处终止程序。
- 如果项目配置是发行(Release),那么就只在异常处提前结束程序。
- 如果项目配置是调试(Debug),就会在异常处提前结束程序 并 弹窗报错。
- 如果项目配置是发行(Release),那么就只在异常处提前结束程序。
- 在异常处终止程序。
- 如果用try-catch来捕获异常,那么程序会在会在异常处提前结束并执行异常代码
-
将main函数中的第一个异常代码取消注释
stack.pop(); // 异常
运行程序。
可以看到程序在异常处结束了,并打印出了异常信息。try-catch也可以嵌套。
-
总结
在设计类或函数时可以用异常来告诉别人或自己,这个类/函数不能这样子用:”这样用是非法的!“。