#include <iostream>
using namespace std;
float Div(int a,int b)//throw(int,float)//表示只允许返回这两种类型异常
{
if(b == 0)
{
short x;
throw x;
}
return a*1.0/b;
}
int main()
{
int a;
int b;
cin>>a>>b;
float result =0.0f;
try//测试语句
{
result = Div(a,b);
}
catch(int)//捕获语句返回的异常
{
cerr << "int b==0" << '\n';
}
catch(float)
{
cerr << "float b==0" << '\n';
}
catch(...)//其他异常返回
{
cerr << "b==0" << '\n';
}
cout<< result;
return 0;
}
堆栈的实现
#include <iostream>
using namespace std;
template <typename Type>
class Stack
{
private:
int capacity;
int top;
Type *idata;
enum
{
STACK_SIZE = 8 //设置堆栈的最小数据结构
};
public:
Stack(int size = STACK_SIZE);
~Stack();
public:
bool Push(const Type &data);
bool Pop(void);
bool IsFull();
bool IsEmpty();
void Show() const;
};
template <typename Type>
void Stack<Type>::Show() const//遍历栈元素,const方法是防止修改栈内元素
{
for (int i = top - 1; i >= 0; i--)
cout << idata[i] << endl;
}
template <typename Type>
bool Stack<Type>::IsFull()//是否满栈
{
return top >= capacity;
}
template <typename Type>
bool Stack<Type>::IsEmpty()//是否是空栈
{
return top <= 0;
}
template <typename Type>
bool Stack<Type>::Pop(void)//弹出
{
if (IsEmpty())
{
cout << "Stack is empty !" << endl;
return false;
}
else
{
top = top -1;
return true;
}
}
template <typename Type>
bool Stack<Type>::Push(const Type &data)//压栈
{
if (IsFull())
{
cout << "Stack full !" << endl;
return false;
}
else
{
idata[top++] = data;
return true;
}
}
template <typename Type>
Stack<Type>::Stack(int size)//初始化
{
capacity = size > STACK_SIZE ? size : STACK_SIZE;
idata = new Type[capacity];
top = 0;
}
template <typename Type>
Stack<Type>::~Stack(/* args */)//析构
{
if (idata != NULL)
delete[] idata;
idata = NULL;
top = 0;
capacity = 0;
}
int main()
{
Stack<int> s(7);
for (int i = 0; i < 10; i++)
{
s.Push(i);
}
s.Show();
return 0;
}